我试图总结一个php多维, 我有这样的数组结构;
Array
(
[0] => Array
(
[product_id] => 1
[product_name] => Product1
[product_price] => 0.90
)
[1] => Array
(
[product_id] => 2
[product_name] => Product2
[product_price] => 1.50
)
[2] => Array
(
[product_id] => 1
[product_name] => Product1
[product_price] => 0.90
)
)
我想编写一个函数,可以很容易地汇总任何重复的条目,并返回一个像这样的新数组(基本上统一了product_price并创建了product_qty字段);
Array
(
[0] => Array
(
[product_id] => 1
[product_name] => Product1
[product_price] => 1.80
[product_qty] => 2
)
[1] => Array
(
[product_id] => 2
[product_name] => Product2
[product_price] => 1.5
[product_qty] => 1
)
)
我尝试过使用array_sum(),array_merge()和array_map()但没有一个返回上面所需的结果。
答案 0 :(得分:1)
这是一些简单的代码:
$summary = array();
foreach ($products as $product) {
if (!isset($summary[$product['product_id']])) {
$summary[$product['product_id']] = array_merge(
$product, array('product_qty' => 1));
} else {
$summary[$product['product_id']]['product_price'] += $product['product_price'];
$summary[$product['product_id']]['product_qty']++;
}
}