我想知道是否有更快的方法来求和,即按数量计算每件元素的重量。
$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/