我的数组(存储在 $r 中)目前看起来是这样的...(每天都有 3 个条目具有相同的日期,在某些情况下还会有更多共享相同日期的条目。)
Array
(
[0] => Array
(
[id] => 1
[date_inserted] => 2020-09-06
[marketplace] => Etsy
[total_stickers] => 11
[total_orders] => 8
[total_value] => 41.62
[1] => Array
(
[id] => 2
[date_inserted] => 2020-09-06
[marketplace] => Woo
[total_stickers] => 2
[total_orders] => 1
[total_value] => 7.98
)
[2] => Array
(
[id] => 3
[date_inserted] => 2020-09-06
[marketplace] => eBay
[total_stickers] => 44
[total_orders] => 40
[total_value] => 115.63
)
[3] => Array
(
[id] => 4
[date_inserted] => 2020-09-07
[marketplace] => Etsy
[total_stickers] => 8
[total_orders] => 4
[total_value] => 34.92
)
[4] => Array
(
[id] => 5
[date_inserted] => 2020-09-07
[marketplace] => Woo
[total_stickers] => 9
[total_orders] => 3
[total_value] => 52.90
)
[5] => Array
(
[id] => 6
[date_inserted] => 2020-09-07
[marketplace] => eBay
[total_stickers] => 23
[total_orders] => 21
[total_value] => 58.03
)
)
我认为如果以日期作为键,并将每个日期的详细信息合并,会更好。此外,[id]不是必需的,"marketplace"可以成为内部数组的键,因此我想要的最终输出应该像这样。
Array
(
[2020-09-06] => Array (
[Etsy] => Array
(
[total_stickers] => 11
[total_orders] => 8
[total_value] => 41.62
)
[Woo] => Array
(
[total_stickers] => 2
[total_orders] => 1
[total_value] => 7.98
)
[eBay] => Array
(
[total_stickers] => 44
[total_orders] => 40
[total_value] => 115.63
)
)
[2020-09-07] => Array (
[Etsy] => Array
(
[total_stickers] => 8
[total_orders] => 4
[total_value] => 34.92
)
[Woo] => Array
(
[total_stickers] => 9
[total_orders] => 3
[total_value] => 52.90
)
[eBay] => Array
(
[total_stickers] => 23
[total_orders] => 21
[total_value] => 58.03
)
)
)
我一直在研究array_merge_recursive,还有array_combine以及类似的问题,但似乎无法弄清楚如何获得我想要的结果。
这是我尝试过的(基于Lawrence Cherone的答案)
$results = [];
foreach (array_column($r, 'date_inserted') as $bydate) {
foreach ($r as $item) {
$results[$bydate][$item['marketplace']] = [
'total_orders' => $item['total_orders'],
'total_stickers' => $item['total_stickers'],
'total_value' => $item['total_value']
];
}
}
但结果是,尽管结构现在看起来正确,但数据本身对于每一天都是相同的(不使用该天的数据)。
这是生成的数组
Array
(
[2020-09-06] => Array
(
[Etsy] => Array
(
[total_orders] => 2
[total_stickers] => 3
[total_value] => 7.83
)
[Woo] => Array
(
[total_orders] => 10
[total_stickers] => 20
[total_value] => 100.38
)
[eBay] => Array
(
[total_orders] => 17
[total_stickers] => 18
[total_value] => 67.36
)
)
[2020-09-07] => Array
(
[Etsy] => Array
(
[total_orders] => 2
[total_stickers] => 3
[total_value] => 7.83
)
[Woo] => Array
(
[total_orders] => 10
[total_stickers] => 20
[total_value] => 100.38
)
[eBay] => Array
(
[total_orders] => 17
[total_stickers] => 18
[total_value] => 67.36
)
)
)
现在我需要让它显示当天的正确数据。