$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);
php array change. How to get the keys of continuous values of an array?
Pergunta
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!
Solução 2
Outras dicas
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.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow