Skip to content

Instantly share code, notes, and snippets.

@codingfox-rus
Last active December 15, 2016 06:18
Show Gist options
  • Save codingfox-rus/b3c7d79256997867d2fc97d7317bff98 to your computer and use it in GitHub Desktop.
Save codingfox-rus/b3c7d79256997867d2fc97d7317bff98 to your computer and use it in GitHub Desktop.
Алгоритм для разбиения массива по последовательностям чисел
<?php
$arr = [2,3,4,8,9,10,14,15,16,20,21,22];
// Вычисляем "пропуски" - индексы массива, на которых последовательность прерывается
$skips = [];
$start = $arr[0];
for ($i = 1; $i < sizeof($arr); $i++) {
if (($arr[$i] - $start) > 1) {
$skips[] = $i;
}
$start = $arr[$i];
}
// Добавляем дополнительный индекс в пропуски для удобства вычислений
$skips[] = sizeof($arr);
// Разделяем массив на подмассивы с учетом пропусков
$chunks = [];
$begin = 0;
foreach ($skips as $skip) {
$chunks[] = array_slice($arr, $begin, $skip - $begin);
$begin = $skip;
}
print_r($chunks);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment