Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Object inside an Array in php

I have one array having multiple objects (say 3 Objects), each having 3 "Key-Value" pairs.

$PredefinedResult is something like this :

[
    {
        "EffectiveStatusId":0,
        "EffectiveStatus":"abc",
        "RecordCount":0
    },
    {
        "EffectiveStatusId":0,
        "EffectiveStatus":"def",
        "RecordCount":0
    },
    {
        "EffectiveStatusId":0,
        "EffectiveStatus":"ghi",
        "RecordCount":0
    }
]

I have another array of objects named $MainResult with values like :

[
    {
        "EffectiveStatusId":1,
        "EffectiveStatus":"abc",
        "RecordCount":7
    },
    {
        "EffectiveStatusId":6,
        "EffectiveStatus":"def",
        "RecordCount":91
    }
]

Expected Result :

I want to replace the similar objects inside $PredefinedResult with the objects from $MainResult and want result like this :

[
    {
        "EffectiveStatusId":1,
        "EffectiveStatus":"abc",
        "RecordCount":7
    },
    {
        "EffectiveStatusId":6,
        "EffectiveStatus":"def",
        "RecordCount":91
    },
    {
         "EffectiveStatusId":0,
         "EffectiveStatus":"ghi",
         "RecordCount":0
    }
]

What I tried :

I tried with this code but it's not giving me the desired result.

$FinalResult = array_replace($PredefineResult,$MainResult);

Can anyone help me on how to get the Expected Result as mentioned above ?

like image 927
Jignesh.Raj Avatar asked Sep 23 '13 12:09

Jignesh.Raj


2 Answers

There's no "built-in" function for this. You're gonna have to loop and compare each manually. array_map seems like an OK choice here:

$PredefinedResult = array_map(function($a) use($MainResult){
    foreach($MainResult as $data){
        if($a->EffectiveStatus === $data->EffectiveStatus){
            return $data;
        }
    }
    return $a;
}, $PredefinedResult);

DEMO: http://codepad.viper-7.com/OHBQK8

like image 143
Rocket Hazmat Avatar answered Sep 28 '22 23:09

Rocket Hazmat


Iterate through the array and manual compare the values as follows.

$res = array();
foreach ($PredefineResult as $result){
    foreach ($MainResult as $mresult){
        if(($result->EffectiveStatus == $mresult->EffectiveStatus) && $mresult->RecordCount!=0){
            $res[] = $mresult;
        }else $res[] = $result;
    }
}
print_r($res);
like image 29
Jeyasithar Avatar answered Sep 28 '22 23:09

Jeyasithar