Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question

2 Answers 2

up vote 0 down vote accepted
$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);
share|improve this answer
    
Wow~your code rocks, simple and clean. Tons of thx! –  tonylevid May 7 at 1:53

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.

share|improve this answer
    
No, your code will change array to this: code array ( 11 => array ( 0 => 2, 1 => 3, 2 => 4, 3 => 10, 4 => 11, ), 12 => array ( 0 => 6, ), 13 => array ( 0 => 7, 1 => 8, ), 14 => array ( 0 => 12, ), ) code –  tonylevid May 6 at 14:11
    
See updated code. –  Jessica May 6 at 14:17
    
Your code works now! Thx! –  tonylevid May 7 at 1:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.