我有一个数组:
$array = [1, 2, 3, 4, 6, 7, 8, 10, 12, 14, 15, 16, 20, 21, 26, 27, 28];
我希望将其转换为字符串,其中序列由短划线分隔。所以上面的数组将成为:1-4, 6-8, 10, 12, 14-16, 20, 21, 26-28
我尝试循环错误并检查前一个数字+ 1是否等于当前数字以确定我是否在循环中。没有完全管理它,它感觉非常低效。关于如何解决这个问题的任何提示和/或想法?
此代码未完成且无法完全运行:
asort($zips);
$formatted = '';
$sequence = [];
$inSequenceLoop = false;
foreach ($zips as $key => $zip) {
// $prev = $key === 0 ? false : $zips[$key - 1];
$current = $zip;
$next = $key === count($zips) - 1 ? false : $zips[$key + 1];
if ($current + 1 === $next) {// || ($next === false && ($prev + 1) === $current)) {
$sequence[] = $current;
$inSequenceLoop = true;
} else {
if ($inSequenceLoop) {
// end of sequence
if (count($sequence) === 1) {
$formatted .= $sequence[0] . ($next ? ',' : '');
} else {
$formatted .= array_shift($sequence) . '-' . array_pop($sequence) . ($next ? ',' : '');
}
// create empty sequence
$inSequenceLoop = false;
$sequence = [];
} else {
// loner
$formatted .= $current . ($next ? ',' : '');
}
}
}
答案 0 :(得分:1)
一种方法是先将数组分成几组:
$pre = $key = 0; // initialize previous value and set key
foreach ($array as $number) {
if ($number > $pre + 1) $key++; // if number is not next in sequence, increment key
$sets[$key][] = $pre = $number; // append to current key and set previous to current
}
然后映射格式化函数以返回范围字符串,并内嵌格式化的范围。
$result = implode(', ', array_map(function($set) {
// return either single element or dash separated first and last element
return count($set) == 1 ? reset($set) : reset($set) . '-' . end($set);
}, $sets));
如果两个元素的范围应格式化为单个元素,格式函数也可以考虑到这一点。
$result = implode(', ', array_map(function($set) {
switch (count($set)) {
case 1: return reset($set);
case 2: return reset($set) . ', ' . $set[1];
default: return reset($set) . '-' . end($set);
}
}, $sets));