peppy peppy - 6 months ago 15
PHP Question

How to merge two multi-dimensional arrays and update duplicates?

I tried to use "array_merge($a,$b)" but this does not work for what I'm doing. Here are two arrays :

$a =
Array
(
[Mike] => Array
(
[100] => Array
(
[quantity] => 1
[attribute] => 1
)

[200] => Array
(
[quantity] => 1
[attribute] => 1
)

[300] => Array
(
[quantity] => 1
[attribute] => 1
)

[400] => Array
(
[quantity] => 1
[attribute] => 1
)

)

)


$b =
Array
(
[Mike] => Array
(
[500] => Array
(
[quantity] => 1
[attribute] => 1
)

[600] => Array
(
[quantity] => 1
[attribute] => 1
)

)

)


The concept is a user "Mike" adds items to their list (100,200,300,400). This list is saved in the database. Mike logs out and starts a new list a few days later as a anonymous guest, adding items (500,600) saved in his session. When he is finished and logs back in, I want to combine the two lists and save the updated list. If I use "array_merge" and since the array key is [Mike], by design it completely replaces $a with $b rather than merging the item numbers together.

How can I combine this? Also if two items are the same in both lists, such as (100,200,300,400) in one list and (100,500) in the second list (item number "100" being the duplicate here). I would like the [quantity] and [attribute] fields of the "100" in the second list to overwrite the those fields for item "100" in the first list.

Thanks
Kind regards

Answer

You can use the below code. Just be sure to put your latest result first. It will give you the result you want.

  $c = $b['Mike']+$a['Mike'];

thanks

Comments