I have two arrays that i want to merge them but combine where date is the same. I managed to merge them but where date is the same it merge them as distinct entries. Here are my 2 arrays: arr1:
[{"y":"2015-03-05","item1":"850","item2":"0"},
{"y":"2015-03-19","item1":"8377","item2":"0"},
{"y":"2015-05-27","item1":"1037","item2":"0"},
{"y":"2015-10-15","item1":"5402","item2":"0"}]
arr2:
[{"y":"2015-04-29","item1":"0","item2":"1008"},
{"y":"2015-05-27","item1":"0","item2":"25"}]
when i use $arr = array_merge($arr1, $arr2);
it merges them but where date is common, in my case 2015-05-27 i want to combine them in "y":"2015-05-27","item1":"1037","item2":"25"
You can try this approach, mapping items array for a date into an associative array with date key, then adding only other items having a non-zero value. See comments in code:
// Make PHP arrays of JSON
$items1 = json_decode('[
{"y":"2015-03-05","item1":"850","item2":"0"},
{"y":"2015-03-19","item1":"8377","item2":"0"},
{"y":"2015-05-27","item1":"1037","item2":"0"},
{"y":"2015-10-15","item1":"5402","item2":"0"}]', true);
$items2 = json_decode('[
{"y":"2015-04-29","item1":"0","item2":"1008"},
{"y":"2015-05-27","item1":"0","item2":"25"}]', true);
// Define an associative array like:
// [
// '<date>' => [ 'item1' => '<n>', 'item2' => "<n>" ],
// ...
// ]
$itemsPerDay = [];
// Loop arrays
foreach (array_merge($items1, $items2) as $array) {
$date = $array['y']; // Get date
if (!isset($itemsPerDay[$date])) {
// If array for date not set in associative array, use full array
$itemsPerDay[$date] = $array;
}
else {
// If array for date already exists, merge only items having a
// non-empty value
$nonEmptyValues = array_filter($array, function($w) { return !empty($w); });
$itemsPerDay[$date] = array_merge($itemsPerDay[$date], $nonEmptyValues);
}
}
// Get values part of associative array
$itemsPerDay = array_values($itemsPerDay);
// Output JSON
echo json_encode($itemsPerDay);
Output (indented for clarity):
[{"y": "2015-03-05", "item1": "850", "item2": "0"},
{"y": "2015-03-19", "item1": "8377", "item2": "0"},
{"y": "2015-05-27", "item1": "1037", "item2": "25"},
{"y": "2015-10-15", "item1": "5402", "item2": "0"},
{"y": "2015-04-29", "item1": "0", "item2": "1008"}]
You could make two passes. 1) array_merge and sort on date 2) Since the array is sorted you can linearly traverse the array to combine and remove duplicate dates