php数组更改。如何获取数组连续值的键?

时间:2014-05-06 14:04:01

标签: php arrays key

我想获得数组连续值的键。 例如:

如何更改此数组:

array(
   2 => 11,
   3 => 11,
   4 => 11,
   6 => 12,
   7 => 13,
   8 => 13,
   10 => 11,
   11 => 11,
   12 => 14
)

到这一个:

array(
    array(2, 3, 4),
    array(6),
    array(7, 8),
    array(10, 11),
    array(12)
)
提前谢谢!

2 个答案:

答案 0 :(得分:1)

已编辑的代码。

<?php
$arr = [2 => 11, 3 => 11,4 => 11, 6 => 12, 7 => 13, 8 => 13, 10 => 11, 11 => 11,12 => 14];

$newArr = [];
$lastVal = null;
$currArr = [];
foreach($arr AS $key=>$value){
    if($lastVal == $value){
        $curArr[] = $key;
    }else{
        if($lastVal != null){
            $newArr[] = $curArr;
        }
        $lastVal = $value;
        $curArr = [$key];
    }
}
$newArr[] = $curArr;

我确信这是一种更优雅的方式。

答案 1 :(得分:0)

$data = array(
   2 => 11,
   3 => 11,
   4 => 11,
   6 => 12,
   7 => 13,
   8 => 13,
   10 => 11,
   11 => 11,
   12 => 14
);

$result = array();
array_walk(
    $data,
    function ($value, $key) use (&$result){
        static $v;
        if ($value == $v) {
            $result[max(array_keys($result))][] = $key;
        } else {
            $result[] = array($key);
        }
        $v = $value;
    }
);

var_dump($result);