I have an array of object "$arr" like this:
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
)
)
What I want to do is rank the value based on the key. If key($arr[$idx+1]) < key($arr[$idx]) then increase value of $arr[idx] by 1. So the results would look like:
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
)
)
this is what I have done so far:
$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;
}
}
}
}
and this is the result I got:
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
)
)
What's the best way to do this? Can anyone guide me? Thanks
Do this with associative array. I can't make an object array right now. If you provide me the object array then i will update my answer.
Try this:
$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);
Result
Array
(
[0] => Array
(
[1] => 2
)
[1] => Array
(
[0] => 1
)
[2] => Array
(
[4] => 5
)
[3] => Array
(
[3] => 4
)
[4] => Array
(
[2] => 3
)
)
I think you want this, let me know.