我的数组有问题。我想对给定的数量求和(
qty
)。
我想得到:
blyszczaca Normal = 6;
czapkoszal Normal = 6;
czapkoszal Luxury = 2;
etola Wolf = 1;
etola Normal = 2;
来自这个数组:
Array
(
[0] => Array
(
[produkt] => blyszczaca
[model] => Normal
[price] => 27.00
[qty] => 2
)
[1] => Array
(
[0] => blyszczaca
[1] => Normal
[2] => 27.00
[3] => 2
)
[2] => Array
(
[0] => blyszczaca
[1] => Normal
[2] => 27.00
[3] => 2
)
[3] => Array
(
[0] => czapkoszal
[1] => Normal
[2] => 41.00
[3] => 2
)
[4] => Array
(
[0] => czapkoszal
[1] => Luxury
[2] => 45.00
[3] => 2
)
[5] => Array
(
[0] => czapkoszal
[1] => Normal
[2] => 41.00
[3] => 2
)
[6] => Array
(
[0] => czapkoszal
[1] => Normal
[2] => 41.00
[3] => 1
)
[7] => Array
(
[0] => czapkoszal
[1] => Normal
[2] => 41.00
[3] => 1
)
[8] => Array
(
[0] => etola
[1] => Wolf
[2] => 47.00
[3] => 1
)
[9] => Array
(
[0] => etola
[1] => Normal
[2] => 39.00
[3] => 1
)
[10] => Array
(
[0] => etola
[1] => Normal
[2] => 39.00
[3] => 1
)
)
您应该创建具有唯一键和计数数量的新数组,例如:
$sums = [];
foreach ($your_array as $item) {
// create a unique key as concatenation of `product` and `model`
$key = $item['product'] . ':' . $item['model'];
// check if such key exists, if not - init key with `0`
if (!isset($sums[$key])) {
$sums[$key] = 0;
}
// add current `qty` to the value of `$sums[$key]`
$sums[$key] += $item['qty']
}
您可以根据输出数组中的
produkt
和 model
创建自定义键。然后,将 qty
添加到该键。尝试以下操作:
// Create a array to store the sum
$sums = array();
// Loop over the input array
foreach ($input as $value) {
// create a custom key based on produkt and model
$key = $value['produkt'] . ' ' . $value['model'];
// initalize the key
$sums[$key] = $sums[$key] ?? 0;
// add the quantity
$sums[$key] += (int)$value['qty'];
}
由于您的输入数组具有不一致的键,因此请在尝试访问数据之前使用
array_values()
重新索引行。
将标识复合值形成为以空格分隔的字符串,其中包含每行的第一个和第二个元素。
代码:(演示)
$result = [];
foreach ($array as $row) {
$row = array_values($row);
$group = "$row[0] $row[1]";
$result[$group] = ($result[$group] ?? 0) + $row[3];
}
var_export($result);