dongyangben6144
dongyangben6144
2014-05-06 14:04
浏览 18
已采纳

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

I want get the keys of continuous values of an array. For example:

how to change this array:

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

to this one:

array(
    array(2, 3, 4),
    array(6),
    array(7, 8),
    array(10, 11),
    array(12)
)

Thx in advance!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douqiao1983
    douqiao1983 2014-05-06 14:26
    已采纳
    $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);
    
    点赞 评论
  • dongsheng1238
    dongsheng1238 2014-05-06 14:05

    Edited Code.

    <?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;
    

    I'm sure there's a more elegant way.

    点赞 评论

相关推荐