I have two arrays which must be merged together on the dt_date
column and I need to declare subscribers
and unsubscribers
in all rows in the result.
$array1 = [
['subscribers' => 2, 'dt_date' => '2014-02-27'],
['subscribers' => 2, 'dt_date' => '2014-02-25'],
['subscribers' => 1, 'dt_date' => '2014-02-07']
];
$array2 = [
['unsubscribers' => 1, 'dt_date' => '2014-02-27'],
['unsubscribers' => 1, 'dt_date' => '2014-02-01']
];
I need to create an array like as follows from the two arrays.
[
['subscribers' => 2, 'unsubscribers' => 1, 'dt_date' => '2014-02-27'],
['subscribers' => 2, 'unsubscribers' => 0, 'dt_date' => '2014-02-25'],
['subscribers' => 1, 'unsubscribers' => 0, 'dt_date' => '2014-02-07'],
['subscribers' => 0, 'unsubscribers' => 1, 'dt_date' => '2014-02-01']
]
I tried
$result = array_merge_recursive($aray1, $array2);
AND
$result = array_merge(
$array1,
array_udiff(
$array2,
$array1,
function($array1,$array2){
return strcmp($array1['dt_date'],$array2['dt_date']);
}
)
);
But the result was not as expected
I find the answer
$result= array_replace_recursive($array1,$array2);
foreach ($result as $key => $value) {
if(!isset($value['unsubscribers']))
$result[$key]['unsubscribers']=0;
if(!isset($value['subscribers']))
$result[$key]['subscribers']=0;
}
Thank you