I have an array like:
[0]=> array(2) { ["item_name_en"]=> string(7) "Salad 1" ["item_description"]=> string(3) "Yum" } [1]=> array(2) { ["item_name"]=> string(7) "Salad 2" ["item_description"]=> string(0) "Yum" }
And another array like:
[0]=> array(2) { ["price"]=> string(2) "15" } [1]=> array(2) { ["price"]=> string(2) "25" }
How do I merge them both into 1 array where the result looks like:
array(3) { ["item_name_en"]=> string(7) "Salad 1" ["item_description"]=> string(3) "Yum" ["price"]=> string(2) "15" }
They will always be the same length but never have the same keys. I already tried array_merge
and also $result = $array1 + $array2;
but that did not produce the desired result. There must be an easy way for this?
Advertisement
Answer
You can do it this way:
Initial data
$a = [ [ "item_name_en"=> "Salad 1", "item_description"=> "Yum" ], [ "item_name"=> "Salad 2", "item_description"=> "Yum" ] ]; $b = [ [ "price"=> "15" ], [ "price"=> "25" ] ];
Result
$c = []; //New array foreach($a as $k => $v){ $c[$k] = array_merge($a[$k], $b[$k]); }
Output
array (size=2) 0 => array (size=3) 'item_name_en' => string 'Salad 1' (length=7) 'item_description' => string 'Yum' (length=3) 'price' => string '15' (length=2) 1 => array (size=3) 'item_name' => string 'Salad 2' (length=7) 'item_description' => string 'Yum' (length=3) 'price' => string '25' (length=2)