【发布时间】:2020-03-13 11:41:19
【问题描述】:
我需要对损坏的系列进行分组。
//Example
$seriesArray = array(1, 2, 3, 5, 7, 8, 11, 12, 15);
//You see numbers are not continuous here.
//Therefore i need to group the above array to seek the below output
预期输出
Series 1 : from 1 to 3
Series 2 : 5
Series 3 : 7 and 8
Series 4 : 11 and 12
Series 5 : 15
在上面的示例中,您可以看到,系列 1 是从 1 到 3 分组的(因为有大于 2 个值),而在系列 2 和 5 中,由于没有连续性,显示单个值。在系列 3 和系列 4 中,它显示了 2 个值,具有两个连续的值。
我尝试过的
function groupSeries($mainArray, $comboArr=array()) {
$getRange = range(min($mainArray), max($mainArray)); //Expected Range
$diffArr = array_diff($getRange, $mainArray); //Difference of what is expected
$ranges = array();
$initiateKey = 0;
foreach($diffArr as $indKey=>$indVal) {
if(!empty($mainArray[$initiateKey])) {
$ranges[] = range($mainArray[$initiateKey], $getRange[$indKey-1]);
$initiateKey = $indKey;
}
}
return showRanges($ranges);
}
function showRanges($getRanges) {
$i = 1;
foreach($getRanges as $indRange) {
$arrCount = count($indRange);
echo "Series $i : ";
switch($arrCount) {
case 1 : echo $indRange[0]; break;
case 2 : echo $indRange[0]." and ".$indRange[1]; break;
default: echo "From ".min($indRange)." to ".max($indRange); break;
}
$i++;
echo "\n";
}
}
$seriesArray = array(1, 2, 3, 5, 7, 8, 11, 12, 15);
groupSeries($seriesArray);
上述系列数组失败,当前输出为
Series 1 : From 1 to 3
Series 2 : 5
Series 3 : 8
Series 4 : From 9 to 15
上述试验适用于某些场景,但在许多情况下都失败了。
【问题讨论】:
-
能否提供一个失败的场景?
-
上面提到的数组本身是失败的,如果有更多的连续性,它工作得很好..