按列对二维数组的行进行分组,并对每组中的另一列求和[重复]

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

对简单数组进行分组时遇到一些问题。想要分组大小和总数量。这些是鞋码。

这是我的数组:

Array
(
[0] => Array
    (
        [sku] => '82368-21'
        [size] => 36
        [quantity] => 1
    )

[1] => Array
    (
        [sku] => '82368-21'
        [size] => 36
        [quantity] => 3
    )

[2] => Array
    (
        [sku] => '82368-22'
        [size] => 38
        [quantity] => 0
    )

[3] => Array
    (
        [sku] => '82368-23'
        [size] => 39
        [quantity] => 2
    )

[4] => Array
    (
        [sku] => '82368-23'
        [size] => 39
        [quantity] => 1
    )
)

如您所见,鞋子有多种尺码和数量。那里 无需删除任何重复项,因为它们都应按大小分组。 我想输出以下内容:

 Array
(
[0] => Array
    (
        [sku] => '82368-21'
        [size] => 36
        [quantity] => 4
    )


[1] => Array
    (
        [sku] => '82368-22'
        [size] => 38
        [quantity] => 0
    )

[2] => Array
    (
        [sku] => '82368-23'
        [size] => 39
        [quantity] => 3
    )
)
php arrays multidimensional-array sum grouping
1个回答
1
投票

您可以使用简单的 foreach 循环来完成此操作:

 $array = array (
    0 => 
    array (
        'size' => 36,
        'quantity' => 1
    ),
    1 => 
    array (
        'size' => 36,
        'quantity' => 3
    ),
    2 => 
    array (
        'size' => 38,
        'quantity' => 0
    ),
    3 => 
    array (
        'size' => 39,
        'quantity' => 2
    ),
    4 => 
    array (
        'size' => 39,
        'quantity' => 1
    )
);

$out = [];

foreach($array as $value){

    $key = $value['size'];
    if(!isset($out[$key])){
        $out[$key] = $value;
    }else{
        $out[$key]['quantity'] += $value['quantity'];
    }
}

print_r($out);

输出

Array
(
    [36] => Array
        (
            [size] => 36
            [quantity] => 4
        )

    [38] => Array
        (
            [size] => 38
            [quantity] => 0
        )

    [39] => Array
        (
            [size] => 39
            [quantity] => 3
        )

)

沙盒

我认为您缺少的是使用

size
作为钥匙。 对于数组,当您想要通过单个值匹配对事物进行分组或组合时,最好采用该值并将其用作数组键。这使得在输出数组中找到该组变得更容易。 完成后,您可以随时使用
array_values
将按键重置为“正常”编号索引。

 //reset the array keys
 $out = array_values($out);
 print_r($out);

输出

Array
(
    [0] => Array
        (
            [size] => 36
            [quantity] => 4
        )

    [1] => Array
        (
            [size] => 38
            [quantity] => 0
        )

    [2] => Array
        (
            [size] => 39
            [quantity] => 3
        )

)

沙盒

干杯

© www.soinside.com 2019 - 2024. All rights reserved.