Jignesh.Raj
Jignesh.Raj

Reputation: 5987

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 ?

Upvotes: 7

Views: 4830

Answers (2)

gen_Eric
gen_Eric

Reputation: 227230

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

Upvotes: 3

Jeyasithar
Jeyasithar

Reputation: 535

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);

Upvotes: 2

Related Questions