将二维数组的行数据按一列进行分组,并对每组中的另一列进行求和,以创建一个平面关联数组

问题描述 投票:0回答:3

我的数组有问题。我想对给定的数量求和(

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
        )

)
php arrays multidimensional-array sum grouping
3个回答
2
投票

您应该创建具有唯一键和计数数量的新数组,例如:

$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']
}

0
投票

您可以根据输出数组中的

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'];
}

0
投票

由于您的输入数组具有不一致的键,因此请在尝试访问数据之前使用

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);
© www.soinside.com 2019 - 2024. All rights reserved.