将多维数组的行按一列分组,并对每组内的另一列值求和[重复]

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

我在 PHP 中有一个像这样的编号数组

原始数组:

Array
        (
            [i] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [qty] => 5
                        )

                    [1] => Array
                        (
                            [id] => 2
                            [qty] => 5
                        )

                    [2] => Array
                        (
                            [id] => 2
                            [qty] => 5
                        )

                    [3] => Array
                        (
                            [id] => 1
                            [qty] => 5
                        )
                    [4] => Array
                        (
                            [id] => 3
                            [qty] => 5
                        )    
                )

        )

我希望它对相同的“id”进行分组,并在有重复的情况下将数量相加,如果“id”是键而不是编号键,我应该能够做到。

我期望的结果是:

Array
        (
            [i] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [qty] => 10
                        )

                    [1] => Array
                        (
                            [id] => 2
                            [qty] => 10
                        )

                    [2] => Array
                        (
                            [id] => 3
                            [qty] => 5
                        )    
                )

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

工作解决方案

<?php 
$your_arr = array(
    array('id' => 1,'qty' => 5),
    array('id' => 2,'qty' => 5),
    array('id' => 2222,'qty' => 5),
    array('id' => 1,'qty' => 5),
    array('id' => 3,'qty' => 5)
);
$new = array();
foreach ($your_array as $r){
    if(!isset($new[$r['id']]))$t=0; //check the current id exist in $new if Not $t = 0; 
    else $t=$r['qty']; //if yes $t's value become the saved value in $new[$r['id']]
    $new[$r['id']]['id'] = $r['id'];
    $new[$r['id']]['qty'] = ($t+$r['qty']); // add the new value with $new[$r['id]]'s value.

}
echo "<pre>";print_r($new);
?>

-1
投票

我认为除了编写自己的方法来处理创建目标数组的原始数组之外,没有其他方法。像这样的东西:

private function processArray($original) {
    $target = array();

    foreach ($original as $originalEntry) {
        foreach ($target as $targetEntry) {
            if ($targetEntry['id'] === $originalEntry['id']) {
                $targetEntry['qty'] = $targetEntry['qty'] + $originalEntry['qty'];
                continue 2;
            }
        }
        $target[] = $originalEntry;
    }
    return $target;
}

我还没有时间测试这个方法,但它应该将所有具有相同

id
的条目连接起来,将所有
qty
字段相加。

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