How in PHP to merge 2 arrays with the same values, and overwrite them?

Example:

First array

Array ( [89] => Array ( [NAME] => "Имя1" [ELEMENTS] => Array ( [2702] => "Значение1" [2703] => "Значение2" [2704] => "Значение3" ) ) [90] => Array ( [NAME] => "Имя2" [ELEMENTS] => Array ( [2694] => "Значение1" [2695] => "Значение2" ) ) ) 

Second array

 Array ( [100] => Array ( [NAME] => "Имя1" [ELEMENTS] => Array ( [2755] => "Значение1" [2756] => "Значение2" ) ) [101] => Array ( [NAME] => "Имя2" [ELEMENTS] => Array ( [2800] => "Значение1" [2801] => "Значение2" ) ) ) 

How to merge them so that we get such an array, that is, the values ​​from the second array overwrite the same values ​​of the first:

 Array ( [100] => Array ( [NAME] => "Имя1" [ELEMENTS] => Array ( [2755] => "Значение1" [2756] => "Значение2" [2704] => "Значение3" ) ) [101] => Array ( [NAME] => "Имя2" [ELEMENTS] => Array ( [2800] => "Значение1" [2801] => "Значение2" ) ) ) 
  • one
    array_merge_recursive() ? - teran
  • unfortunately, he merges them and replaces nothing but keys with 0.1 .. - Alexey Komzarev
  • Yes, it should reset numeric keys. and what merge algorithm do you have? you have for Name1 for values ​​different id, on what principle do you want to merge? - teran
  • There are 2 arrays. 1st standard values, 2nd new. The 3rd array is standard + new. That is all that in the 2nd array replaces what is with the same value in the first one. Keys are Id-shniki - Alexey Komzarev

1 answer 1

Usually arrays are merged not by values, but by keys. For such a structure of arrays ( $adata , $bdata ), you can solve the problem, for example, as follows.

 $result = []; foreach($adata as $a) { foreach ($bdata as $k => $b) { if ($a['NAME'] != $b['NAME']) continue; $fa = array_flip($a['ELEMENTS']); $fb = array_flip($b['ELEMENTS']); $el = array_flip(array_merge($fa, $fb)); $result[$k] = ['NAME' => $a['NAME'], 'ELEMENTS' => $el]; } }