这是我的数组
[Computers] => Array
(
[0] => Array
(
[product_id] => 78
[price] => 999.99
[quantity] => 2
)
[1] => Array
(
[product_id] => 70
[price] => 49.99
[quantity] => 6
)
)
[Scanners] => Array
(
[0] => Array
(
[product_id] => 65
[price] => 99.99
[quantity] => 7
)
[1] => Array
(
[product_id] => 70
[price] => 149.99
[quantity] => 5
)
[2] => Array
(
[product_id] => 70
[price] => 10.99
[quantity] => 1
)
)
我一直在寻找一种基于内部数组
来总计外部数组值的方法所以例如Computers
数组有两个产品,我需要根据数量得到总数。所以例如(999.99 * 2)+(49.99 * 6)= 2299.92用于计算机阵列等等......
答案 0 :(得分:2)
这是一个未经测试的解决方案,但我不明白为什么它不起作用
$sum = 0;
foreach($array as $key => $value) {
$sum += $value['quantity'] * $value['price'];
}
答案 1 :(得分:2)
这是一种替代方法,maps产品小计,然后将外部数组中每个项目的子总和相加。
$totals = array_map(function($group){
return array_sum(array_map(function($product) {
return $product['price'] * $product['quantity'];
}, $group));
}, $array);
var_dump($totals, array_sum($totals));
答案 2 :(得分:0)
试试这段代码:
$sum=0;
foreach ($computers as $pc) {
$sum += ($pc["price"] * $pc["quantity"]);
}
答案 3 :(得分:0)
$total = 0;
for( $i = 0; $i < count( Computers ); $i++ ){
$total += ( Computers[$i]['price'] * Computers[$i]['quantity'] );
}