Grouping array with consecutive keys
I've an array like this -
Array
(
[16] => 424
[17] => 404
[18] => 416
[21] => 404
[22] => 456
[23] => 879
[28] => 456
[29] => 456
[32] => 123
[35] => 465
)
The output of this array would be
Array
(
[0] => Array
( ['start'] => 16
['stop'] => 19
)
[1] => Array
( ['start'] => 21
['stop'] => 24
开发者_JS百科 )
[2] => Array
(
['start'] => 28
['stop'] => 30
)
[3] => Array
(
['start'] => 32
['stop'] => 33
)
[4] => Array
(
['start'] => 35
['stop'] => 36
)
)
I don't really need the values. Just grouping the keys.
The 'start' value should be the 'start' value itself. Whereas, the 'stop' value should be a consecutive integer.
And if consecutive integer doesn't exist for a particular key(like for [32] and [35]), 'stop' should be the integer+1 (same as above) .
Thank you all for help.
reset($arr);
$lastKey = key($arr);
$ansIndex = -1;
$ans = array();
foreach ($arr as $k=>$v)
{
if ($k != $lastKey + 1)
{
$ansIndex++;
$ans[$ansIndex]['start'] = $k;
}
$ans[$ansIndex]['stop'] = $k+1;
$lastKey = $k;
}
EDIT - changed $k to $k+1 for the stop
indexes to reflect change in your question
EDIT - noticed i had a line of code within both if
and else
. taking it out of conditional since it runs regardless.
精彩评论