Skip to content

Instantly share code, notes, and snippets.

@aginev
Created March 11, 2016 07:54
Show Gist options
  • Select an option

  • Save aginev/027d9ace004321112252 to your computer and use it in GitHub Desktop.

Select an option

Save aginev/027d9ace004321112252 to your computer and use it in GitHub Desktop.
Split array into a specific number of chuncks
<?php
/**
* Split array into a specific number of chuncks
*
* @param array $data
* @param $chunks Number of chunks
* @return array
*/
function partition(Array $data, $chunks) {
$result = array();
$per_chunk = ceil(count($data) / $chunks);
$counter = 0;
foreach ($data as $row) {
$result[floor($counter / $per_chunk)][] = $row;
$counter++;
}
return $result;
}
@aginev

aginev commented Mar 11, 2016

Copy link
Copy Markdown
Author

Input:

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

Output:

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

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

    [2] => Array
        (
            [0] => 7
            [1] => 8
        )

)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment