Split an Array into N Arrays – PHP-ThrowExceptions

Exception or error:

I have an array of 18 values:

$array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r');

I want to split this array into 12 different arrays so it should look like this:

array(
    0 => array('a', 'b'),
    1 => array('c', 'd'),
    2 => array('e', 'f'),
    3 => array('g', 'h'),
    4 => array('i', 'j'),
    5 => array('k', 'l'),
    6 => array('m'),
    7 => array('n'),
    8 => array('o'),
    9 => array('p'),
   10 => array('q'),
   11 => array('r')
)

My function doesn’t seem to work

function array_split($array, $parts){
    return array_chunk($array, ceil(count($array) / $parts));
}

$result = array_split($array, 12);

because I get 9 different arrays instead of 12. It would return

array(
    0 => array('a', 'b'),
    1 => array('c', 'd'),
    2 => array('e', 'f'),
    3 => array('g', 'h'),
    4 => array('i', 'j'),
    5 => array('k', 'l'),
    6 => array('m', 'n'),
    7 => array('o', 'p'),
    8 => array('q', 'r')
)

How would I go about doing this? Thanks.

How to solve:

This simple function would work for you:

Usage

$array = range("a", "r"); // same as your array
print_r(alternate_chunck($array,12));

Output

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
            [1] => f
        )

    [3] => Array
        (
            [0] => g
            [1] => h
        )

    [4] => Array
        (
            [0] => i
            [1] => j
        )

    [5] => Array
        (
            [0] => k
            [1] => l
        )

    [6] => Array
        (
            [0] => m
        )

    [7] => Array
        (
            [0] => n
        )

    [8] => Array
        (
            [0] => o
        )

    [9] => Array
        (
            [0] => p
        )

    [10] => Array
        (
            [0] => q
        )

    [11] => Array
        (
            [0] => r
        )

)

Update The above might not be useful for most cases … here is another type of chunk

$array = range("a", "r"); // same as your array
print_r(fill_chunck($array, 5));

Output

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
            [2] => c
            [3] => d
        )

    [1] => Array
        (
            [0] => e
            [1] => f
            [2] => g
            [3] => h
        )

    [2] => Array
        (
            [0] => i
            [1] => j
            [2] => k
            [3] => l
        )

    [3] => Array
        (
            [0] => m
            [1] => n
            [2] => o
            [3] => p
        )

    [4] => Array
        (
            [0] => q
            [1] => r
        )

)

This would make sure the group at no time is more that 5 elements where the other one has no limitation

Function Used

function alternate_chunck($array, $parts) {
    $t = 0;
    $result = array();
    $max = ceil(count($array) / $parts);
    foreach(array_chunk($array, $max) as $v) {
        if ($t < $parts) {
            $result[] = $v;
        } else {
            foreach($v as $d) {
                $result[] = array($d);
            }
        }
        $t += count($v);
    }
    return $result;
}


function fill_chunck($array, $parts) {
    $t = 0;
    $result = array_fill(0, $parts - 1, array());
    $max = ceil(count($array) / $parts);
    foreach($array as $v) {
        count($result[$t]) >= $max and $t ++;
        $result[$t][] = $v;
    }
    return $result;
}

Answer:

You said:

I have 13 categories in the DB that I want to group them into 12
arrays. If there are more than 12 categories, which there are, then
insert the remaining values starting from the first array.

This works, but what should be the output if you have more elements in the input array?

$array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm');

function s($array, $am) {
    $r = array();
    $d = count($array) - $am+1;
    foreach ($array as $k => $v) {
        if ($k < $d) {
            if (!isset($r[0])) {
                $r[0] = array($v);
            } else {
                $r[0] = array_merge($r[0], array($v));
            }
        } else {
            $r[] = array($v);
        }
    }

    return $r;
}

will return

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
        )

    [2] => Array
        (
            [0] => d
        )

    [3] => Array
        (
            [0] => e
        )

    [4] => Array
        (
            [0] => f
        )

    [5] => Array
        (
            [0] => g
        )

    [6] => Array
        (
            [0] => h
        )

    [7] => Array
        (
            [0] => i
        )

    [8] => Array
        (
            [0] => j
        )

    [9] => Array
        (
            [0] => k
        )

    [10] => Array
        (
            [0] => l
        )

    [11] => Array
        (
            [0] => m
        )

)

Answer:

Allow me to be the first to offer a math-based, loopless solution.

The magic in the math is determining which portion of elements belongs in the first set of chunks where all columns are filled in each row versus which elements belong in the second set (if the set should even exist) where all columns except the right-most column are filled.

Let me draw what I’m talking about. The > marks the division between the two chunked arrays.

$size = 9;        -------------    $size = 9;        -------------
$maxrows = 4;   1 | A , B , C |    $maxrow = 3;      | A , B , C |
$columns = 3;   > |-----------|    $columns = 3;   1 | D , E , F |
$fullrows = 1;    | D , E |        $fullrows = 3;    | G , H , I |
                2 | F , G |                        > -------------
                  | H , I |                        2      n/a
                  ---------


$size = 18;        ---------    $size = 17;       -------------------------------------
$maxrows = 12;     | A , B |    $maxrows = 2;   1 | A , B , C , D , E , F , G , H , I |
$columns = 2;      | C , D |    $columns = 9;   > -------------------------------------
$fullrows = 6;     | E , F |    $fullrows = 1;  2 | J , K , L , M , N , O , P , Q |
                 1 | G , H |                      ---------------------------------
                   | I , J |
                   | K , L |
                 > ---------
                   | M |
                   | N |
                   | O |
                 2 | P |
                   | Q |
                   | R |
                   -----

Code: (Demo)

function double_chunk($array, $maxrows) {
    $size = sizeof($array);
    $columns = ceil($size / $maxrows);
    $fullrows = $size - ($columns - 1) * $maxrows;

    if ($fullrows == $maxrows) {
        return array_chunk($array, $fullrows);  // all columns have full rows, don't splice
    }
    return array_merge(
               array_chunk(
                   array_splice($array, 0, $columns * $fullrows),  // extract first set to chunk
                   $columns
               ),
               array_chunk($array, $columns - 1)   // chunk the leftovers
           );
}
var_export(double_chunk(range('a', 'i'), 3));

If you don’t mind the iterated array_splice() calls, this is more brief and perhaps easier to follow (…perhaps not):

Code: (Demo)

function custom_chunk($array, $maxrows) {
    $size = sizeof($array);
    $columns = ceil($size / $maxrows);
    $fullrows = $size - ($columns - 1) * $maxrows;

    for ($i = 0; $i < $maxrows; ++$i) {
        $result[] = array_splice($array, 0, ($i < $fullrows ? $columns : $columns - 1));
    }
    return $result;
}
var_export(custom_chunk(range('a', 'r'), 12));

Answer:

You can use array_chunk and array_merge for this problem:

<?php 

$array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r');
$chunked_arr = array_chunk($array,12);
$j = 0;
for($i = 0; $i < count($chunked_arr[0]); $i++){
    if(!($i % 2 == 0)){
        $first_combined[$j][$i % 2] = $chunked_arr[0][$i];
        $j++;
    } else {
    $first_combined[$j][$i % 2] = $chunked_arr[0][$i];
    }
}

$merged_array = array_merge($first_combined, $chunked_arr[1]); 

echo '<pre>';
print_r($merged_array);
 ?>

And You will get the result like this:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
            [1] => f
        )

    [3] => Array
        (
            [0] => g
            [1] => h
        )

    [4] => Array
        (
            [0] => i
            [1] => j
        )

    [5] => Array
        (
            [0] => k
            [1] => l
        )

    [6] => m
    [7] => n
    [8] => o
    [9] => p
    [10] => q
    [11] => r
)

This is what exactly you want.

Live Demo Here>>

Answer:

ceil(count($array) / $parts) would give 2, so each array is being filled up with 2 items until you dont have 2 items left. hence the last one has 1 item. this will work when you have a huge amount of data in the array, but not so much when you have a small amount of data.

Answer:

What you are describing is not what array_chunk is made for. You should use array_slice() and calculate yourself which parts of the array you want to end up as new arrays. (and use a for loop to iterate over your original array)

Update:

Some calculations that could help you:

minimum_fill = floor(array_length / nr_buckets)
bigger_buckets_amount = array_length - (minimum_fill / nr_buckets)

Algorithm to fill buckets:
Loop over the array, fill the first bigger_buckets_amount amount of buckets with (minimum_fill + 1), fill the rest of the buckets with minimum_fill

Answer:

Compile that and see if it does for you:

<?php

$array = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm');

$sliceA = 0;
$sliceB = 2;

$final = array(array_slice($array, $sliceA, $sliceB));


for ($i=$sliceB; $i<sizeof($array); $i++)
{
    $final[$sliceB-1] = array($array[$i]);
    $sliceB++;
}

var_dump($final);

Answer:

<?php
$array = range('a','r');
$length = array(2=>6,1=>6); // 2=>6 means -- first six elements of new array will have 2 elements each and then, 1=>6 means -- next six elements of new array will have 1 element each
$target = array(); // or use []  in PHP 5.4
foreach($length as $i=>$times) {
    while($times>0){
        $target[] = array_splice($array, 0, $i);
        $times--;
    }
}
print_r($target);
?>

Answer:

This will do it for you!
Here, I used my function smallify() to break an array of 15 elements into 3 arrays of 5 elements each.

<?php

$bigArray = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);

echo ("<pre>");
print_r (smallify($bigArray, 3));
echo ("<pre/>");


function smallify($arr, $numberOfSlices){

  $sliceLength = sizeof($arr) /$numberOfSlices;
  for($i=1; $i<=$numberOfSlices; $i++){

       $arr1 = array_chunk($arr, $sliceLength*$i);
       return $arr1;
       unset($arr1);

   }

}
?>

Result

Array
(
[0] => Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
        [3] => 4
        [4] => 5
    )

[1] => Array
    (
        [0] => 6
        [1] => 7
        [2] => 8
        [3] => 9
        [4] => 10
    )

[2] => Array
    (
        [0] => 11
        [1] => 12
        [2] => 13
        [3] => 14
        [4] => 15
    )

)

Answer:

I believe the problem is that you are using a size of 2 when using array_chunk. This ensures that each new array created has two items in it if possible. This causes the function to run out of variables to put into the new arrays by the time you get to 10. You can find the manual on the function here http://php.net/manual/en/function.array-chunk.php Hope this helps

Answer:

Can you try using the following simple function?

$cols = array2cols($array,12);

function array2cols($array,$n){
    $groups = array();
    for($i=0;$i<$n;$i++){
        $groups[$i] = array();
    }
    $col = 0;
    foreach($array as $row){
        $groups[$col][] = $row;
        $col = ($col+1)%$n;
    }
    return $groups;
}

Leave a Reply

Your email address will not be published. Required fields are marked *