如何在PHP中压缩整数数组?

时间:2017-07-03 17:36:26

标签: php arrays

所以我有一个整数数组:<1, 2, 3, 9, 10, 11, 14>,我希望以这种格式加入:<1-3, 9-11, 14>

我是PHP的新手并尝试通过遍历数组来实现这一点:

function pasteTogether($val)
    {
        $newVals = array();
        $min = $val[0];
        $max = $val[1];
        $counter = 0;
        for ($i = 0; $i < count($val); $i++)
        {
            if ($val[$i + 1] === $val[$i] + 1)
            {
                $max = $val[$i + 1];
            }
            else
            {
                $tempVal = $min."-".$max;
                $newVals[$counter] = $tempVal;
                $counter++;
                $min = $val[$i];
            }
        }
        return $newVals;
    }

然而,当我运行此代码时,我得到&lt; 1-3,3-11,11-11,14-14&gt;

3 个答案:

答案 0 :(得分:0)

PHP致命错误:第36行的../learning.php超出了30秒的最长执行时间

因为for循环永远不会结束,所以增加$ val而不是$ i

$array = array(1, 2, 3, 9, 10, 11, 14);


function pasteTogether($val)
{
    $newVals = array();
    $min = $val[0];
    $max = $val[1];
    $counter = 0;
    for ($i = 0; $i < count($val); $i++)
    {
        if ($val[$i + 1] === $val[$i] + 1)
        {
            $max = $val[$i + 1];
        }
        else
        {
            $tempVal = $min."-".$max;
            $newVals[$counter] = $tempVal;
            $counter++;
            $min = $val[$i];
        }
    }
    return $newVals;
}

pasteTogether($array);

答案 1 :(得分:0)

我一直在玩这个有趣的问题,并找到了另一个解决方案。所以,如果有人有兴趣:

$arr=array(1, 2, 3, 9, 10, 11, 14, 15, 16, 18);
$v0=$dif=null;$rows=array();

foreach ($arr as $i => $v) {
 if ($dif!=($d=($v-$i))){
   if ($v0) $rows[]="$v0-".$arr[$i-1];
   $v0=$v;
   $dif=$d;
 }
}
$rows[]="$v0-".($d==$dif?$arr[$i]:$v0);

print_r($rows);

我在数组中添加了一些数字,结果如下:

$rows = Array
(
    [0] => 1-3
    [1] => 9-11
    [2] => 14-16
    [3] => 18-18
)

你可以在这里找到一个小小的演示:http://rextester.com/ABC25608

答案 2 :(得分:0)

这有效:

function pasteTogether($val)
{
    $compacted = [];
    $min       = null;
    $max       = null;

    $format = function ($a, $b) {
        return ($a < $b ? "$a-$b" : $a);
    };

    foreach ($val as $current) {
        if ($min === null) {
            $min = $current;
            $max = $current - 1;
        }

        if ($current == $max + 1) {
            $max++;
        } else {
            $compacted[] = $format($min, $max);
            $min         = $current;
            $max         = $current;
        }
    }

    $compacted[] = $format($min, $max);

    return $compacted;
}

echo '<', implode(', ', pasteTogether([1, 2, 3, 9, 10, 11, 14])), '>';

输出: &lt; 1-3,9-11,14&gt;