this code may be solve your problems:
$arr = array("1" => "1", "2" => "2", "4" => "4", "5" => "5", "8" => "8", "9" => "9", "10" => "10", "11" => "11", "12" => "12", "16" => "16");
$arr_result = array();
$arr_keys = array_keys($arr);
$start = intval($arr_keys[0]);
$end = intval($arr_keys[count($arr_keys)-1]);
$group_idx = 0;
$idx = $start;
foreach($arr_keys as $x => $key) {
if (intval($key) == intval($idx)) {
$arr_result[$group_idx][$key] = $arr[$key];
$idx++;
} else {
$group_idx++;
$arr_result[$group_idx][$key] = $arr[$key];
$idx = intval($key) + 1;
}
}
print_r($arr_result);
i tested it, and run perfectly like your request :). And the result is:
Array
(
[0] => Array
(
[1] => 1
[2] => 2
)
[1] => Array
(
[4] => 4
[5] => 5
)
[2] => Array
(
[8] => 8
[9] => 9
[10] => 10
[11] => 11
[12] => 12
)
[3] => Array
(
[16] => 16
)
)
solved PHP – split an array based on missing keys [closed]