You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP二维数组每行指定字段相乘后计算总金额如何实现

PHP 二维数组行乘积求和解决方案

你需要逐行计算Price和Quantity的乘积再累加,这里提供3种常用实现方式:

方法1:使用array_reduce(最简洁推荐)

专门用于数组迭代累加的内置函数,不需要额外遍历:

// PHP 5.3+ 兼容写法
$total = array_reduce($datas, function($carry, $item) {
    return $carry + $item['Price'] * $item['Quantity'];
}, 0);

// 输出保留两位小数的金额
echo number_format($total, 2);

如果是PHP7.4及以上版本,可以用箭头函数简化:

$total = array_reduce($datas, fn($carry, $item) => $carry + $item['Price'] * $item['Quantity'], 0);
echo number_format($total, 2);

方法2:foreach 遍历(新手友好易理解)

逻辑直观,适合需要额外处理每行数据的场景:

$total = 0;
foreach ($datas as $item) {
    $total += $item['Price'] * $item['Quantity'];
}
echo number_format($total, 2);

说明

你原来的写法array_sum(array_column($datas, 'Price'))仅提取了所有Price字段直接求和,没有和对应行的Quantity相乘,因此无法得到正确的总金额。


内容的提问来源于stack exchange,提问作者Maman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 21:45:04