I wonder if there is a faster way to sum i.e. the weight of each item by qty.
$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;
If i would not need the qty offset, i just could use
array_sum(array_column($items, 'weight'))
But this wont work ofc in this example.
Anybody has an idea if and how this could be done faster?
Thanks /cottton
EDIT
Test script:
$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