Skip to content

Instantly share code, notes, and snippets.

@veloxy
Created February 21, 2014 13:41
Show Gist options
  • Save veloxy/9134425 to your computer and use it in GitHub Desktop.
Save veloxy/9134425 to your computer and use it in GitHub Desktop.
Create chunks of variable sizes
<?php
if (!function_exists('array_chunk_uneven')) {
function array_chunk_uneven(array $array, array $sizes)
{
while (list($key, $size) = each($sizes)) {
$chunks[] = array_slice($array, 0, $size);
$array = array_values(array_slice($array, $size, count($array)));
if ($array && $key == (count($sizes) - 1)) {
reset($sizes);
} elseif (empty($array)) {
break;
}
}
return $chunks;
}
}
/*
input: array('item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9'), array(1, 3))
output: Array
(
[0] => Array
(
[0] => item1
)
[1] => Array
(
[0] => item2
[1] => item3
[2] => item4
)
[2] => Array
(
[0] => item5
)
[3] => Array
(
[0] => item6
[1] => item7
[2] => item8
)
[4] => Array
(
[0] => item9
)
)
----
input: array('item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9'), array(5, 1))
output:
Array
(
[0] => Array
(
[0] => item1
[1] => item2
[2] => item3
[3] => item4
[4] => item5
)
[1] => Array
(
[0] => item6
)
[2] => Array
(
[0] => item7
[1] => item8
[2] => item9
)
) */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment