How to merge array of arrays by key in php? -
so questions of nature have been asked 1000 times on stack overflow, none of them i've searched through far address issue i'm having. have 2 arrays this:
$cupcake_sales = [ ['date' => '05/09/1992', 'num_cupcakes_sold' => 30 ], ['date' => '05/11/1992', 'num_cupcakes_sold' => 25 ], ];
and array this:
$cupcake_revenue = [ ['date' => '05/10/1992', 'revenue' => '$40'], ['date' => '05/11/1992', 'revenue' => '$100'], ];
what need array this:
$cupcake_sales_revenue = [ ['date' => '05/09/1992', 'num_cupcakes_sold' => 30], ['date' => '05/10/1992', 'num_cupcakes_sold' => 25, 'revenue' => '$40'], ['date' => '05/11/1992', 'revenue' => '$100'], ];
any way of doing this?
this should work you:
(here loop through both arrays array_map()
, if date same merge 2 arrays array_merge()
, assign results array. if different append both arrays result array in current iteration.)
<?php $cupcake_sales_revenue = []; array_map(function($v1, $v2)use(&$cupcake_sales_revenue){ if($v1["date"] == $v2["date"]) { $cupcake_sales_revenue[] = array_merge($v1, $v2); } else { $cupcake_sales_revenue[] = $v1; $cupcake_sales_revenue[] = $v2; } }, $cupcake_sales, $cupcake_revenue); print_r($cupcake_sales_revenue); ?>
output:
array ( [0] => array ( [date] => 05/09/1992 [num_cupcakes_sold] => 30 ) [1] => array ( [date] => 05/10/1992 [revenue] => $40 ) [2] => array ( [date] => 05/11/1992 [num_cupcakes_sold] => 25 [revenue] => $100 ) )