php获取一堆数字里面的区间段。
<?php /** * @param array $numer_list * @return array */ function getBeginEndFromNumberList(array &$numer_list) { if (!$numer_list) { return []; } sort($numer_list); $min = $numer_list[0]; $max = end($numer_list); $block_list = []; $key = $min; for ($i = $min; $i <= $max; $i ++) { if (!in_array($i, $numer_list)) { $key = $i; } else { $block_list[$key][] = $i; } } foreach ($block_list as $key => &$block) { if (count($block_list[$key]) > 1) { $block_list[$key] = min($block_list[$key]) . ',' . max($block_list[$key]); } else { $block_list[$key] = (string)reset($block); } } return array_values($block_list); }
使用如下:
$number_list = [1, 2, 3, 4, 6, 7, 13, 19, 20, 21]; echo '<pre>';print_r(getBeginEndFromNumberList($number_list)); //打印结果如下 Array ( [0] => 1,4 [1] => 6,7 [2] => 13 [3] => 19,21 )