PHP 按 item.qty 求和数组值

标签 php foreach array-column array-sum

我想知道是否有更快的方法来求和,即按数量计算每件元素的重量。

$items = [
    [
        'qty'    => 1,
        'weight' => 1,
    ],
    [
        'qty'    => 2,
        'weight' => 1,
    ],
    [
        'qty'    => 3,
        'weight' => 1,
    ],
];

$totalWeight = 0.0;
foreach ($items as $item) {
    $totalWeight += $item['weight'] * $item['qty'];
}
echo $totalWeight . PHP_EOL;

如果我不需要数量偏移,我就可以使用

array_sum(array_column($items, 'weight'))

但是在这个例子中这不起作用。

有人知道是否以及如何可以更快地完成此任务吗?

谢谢 /棉质

编辑

测试脚本:

$items = [];
for ($i = 0; $i < 1000; $i++) {
    $items[] = [
        'foo'    => 1,
        'qty'    => $i,
        'bar'    => 2,
        'weight' => $i,
        'baz'    => 3,
    ];
}
$totalWeight = 0.0;


$start = microtime(true);
for ($i = 0; $i < 10000; $i++) {
    $totalWeight = 0.0;
    foreach ($items as $item) {
        $totalWeight += $item['weight'] * $item['qty'];
    }
}
$elapsed = sprintf('%f', microtime(true) - $start);
echo "Elapsed: {$elapsed}\r\n";
echo "Total weight: {$totalWeight}\r\n";
// Elapsed: 0.744311
// Total weight: 332833500

最佳答案

使用https://www.w3schools.com/php/func_array_reduce.asp

    <?php
    $items = [
        [
            'qty'    => 1,
            'weight' => 1,
        ],
        [
            'qty'    => 2,
            'weight' => 1,
        ],
        [
            'qty'    => 3,
            'weight' => 1,
        ],
    ];


    $totalWeight = array_reduce($items, 
        function($acc, $e) { return $acc + ($e['weight'] * $e['qty']); });
    echo $totalWeight . PHP_EOL;

?>

关于PHP 按 item.qty 求和数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50160741/

相关文章:

php - 从对象数组的单列创建逗号分隔的字符串

php - 在每个 foreach 循环迭代中包含 Blade 模板重复

php - 使用 Guzzle 通过 Curl 请求传递客户端证书

php - 如何通过 PHP 处理 SELECT 1 的结果?

php - Facebook PHP SDK oauth 1.0 还是 2.0

javascript - 为什么 `Loop`不止一次写入

c# - foreach 在循环函数结果时如何工作?

php - 在 PHP5 中运行 PHP7 的代码有哪些替代方案

PHP "Remember Me"安全漏洞?