gpt4 book ai didi

php - 如何合并两个数组,但在日期常见的地方合并它们

转载 作者:行者123 更新时间:2023-11-29 22:29:16 24 4
gpt4 key购买 nike

我有两个数组,我想合并它们,但合并日期相同的地方。我设法合并它们,但如果日期相同,它将它们合并为不同的条目。这是我的 2 个数组: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"}]

当我使用 $arr = array_merge($arr1, $arr2); 时,它会合并它们,但日期很常见,在我的情况下 2015-05-27 我想将它们合并到 "y":"2015-05-27","item1":"1037","item2":"25"

最佳答案

您可以尝试这种方法,将日期的项目数组映射到具有 date 键的关联数组,然后仅添加具有非零值的其他项目。请参阅代码中的注释:

// 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);

输出(为了清晰起见,缩进):

[{"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"}]

关于php - 如何合并两个数组,但在日期常见的地方合并它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29952168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com