我有一个对象数组" $ arr"像这样:
Array
(
[0] => stdClass Object
(
[1] => 1
)
[1] => stdClass Object
(
[0] => 1
)
[2] => stdClass Object
(
[4] => 2
)
[3] => stdClass Object
(
[3] => 2
)
[4] => stdClass Object
(
[2] => 3
)
)
我想要做的是根据密钥对值进行排名。如果键($ arr [$ idx + 1])< key($ arr [$ idx])然后将$ arr [idx]的值增加1.所以结果看起来像:
Array
(
[0] => stdClass Object
(
[1] => 2
)
[1] => stdClass Object
(
[0] => 1
)
[2] => stdClass Object
(
[4] => 5
)
[3] => stdClass Object
(
[3] => 4
)
[4] => stdClass Object
(
[2] => 3
)
)
这是我到目前为止所做的:
$arrIdx2=[];
foreach($arrIdx as $key=>$value){
$newVal = new stdClass();
$newVal->$key = $value;
$arrIdx2[] = $newVal;
}
foreach($arrIdx2 as $key=>$value){
$i= key((array)$value);
$m = $value->$i; //get the first value
for($j = $key+1; $j< $len; $j++){
$i2 = key((array)$arrIdx2[$j]); //get the key of second value
$n = $arrIdx2[$j]->$i2;
if($n == $m){
if($i2 < $i){
$arrIdx2[$key]->$i += 1;
}
}
}
}
这是我得到的结果:
Array
(
[0] => stdClass Object
(
[1] => 2
)
[1] => stdClass Object
(
[0] => 1
)
[2] => stdClass Object
(
[4] => 3
)
[3] => stdClass Object
(
[3] => 2
)
[4] => stdClass Object
(
[2] => 3
)
)
最好的方法是什么?谁能指导我?感谢
答案 0 :(得分:0)
使用关联数组执行此操作。我无法创建一个对象数组 马上。如果您提供对象数组,那么我将更新我的答案。
试试这个:
$arr = array(
array("1" => 1),
array("0" => 1),
array("4" => 2),
array("3" => 2),
array("2" => 3)
);
$out = array();
$first = key(current($arr));
$end = key(end($arr));
foreach($arr as $key => $val){
$comp = (key($val) == $end) ? $end : key($arr[$key+1]);
if($comp <= key($val))
$out[$key][key($val)] = key($val) + 1;
else
$out[$key][key($val)] = $val[key($val)];
}
echo '<pre>';
print_r($out);
<强>结果强>
Array
(
[0] => Array
(
[1] => 2
)
[1] => Array
(
[0] => 1
)
[2] => Array
(
[4] => 5
)
[3] => Array
(
[3] => 4
)
[4] => Array
(
[2] => 3
)
)
我想你想要这个,请告诉我。