Replace object inside array in php

I have one array that has several objects (for example, 3 objects), each of which has 3 key-value pairs.

$PredefinedResult looks 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 called $MainResult with values, for example:

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

Expected Result:

I want to replace similar objects inside $PredefinedResult with objects from $MainResult and get the result as follows:

 [ { "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 did not give me the desired result.

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

Can someone help me on how to get the expected result as above?

+6
source share
2 answers

There is no built-in function for this. You will have to quote and compare each manually. array_map looks like an OK choice:

 $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

+2
source

Iterating through an array and a manual compares 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); 
+2
source

Source: https://habr.com/ru/post/954417/


All Articles