从多维数组中删除重复值并对它们求和

时间:2015-05-16 09:23:31

标签: php arrays multidimensional-array

假设我有一个这样的数组:

   Array
    (
        [0] => Array
        (
            [0] => A
            [1] => 20
        )

        [1] => Array
        (
            [0] => B
            [1] => 10
        )

        [2] => Array
        (
            [0] => G
            [1] => 5
        )

        [3] => Array
        (
            [0] => A
            [1] => 15
        )


    )

我想删除重复的值并只汇总一行数组: 我想要的是什么:

   Array
    (
        [0] => Array
        (
            [0] => A
            [1] => 35 // <= sum : 20 + 15
        )

        [1] => Array
        (
            [0] => B
            [1] => 10
        )

        [2] => Array
        (
            [0] => G
            [1] => 5
        )



    )

我之前已经阅读了this个问题。

更新

while($row = $stmt->fetch()){

    $arr = array(
        'GoodMainCode'=>persian_sql_to_php($row['GoodMainCode']), // <= like A in the example
        'title'=> persian_sql_to_php($row['GoodName']),
        'author'=>persian_sql_to_php($row['moalef']),
        'publisher'=>persian_sql_to_php($row['Nasher']),
        'translator'=>persian_sql_to_php($row['Motarjem']),
        'price'=>persian_sql_to_php($row['SellPrice1']),
        'isbn'=>persian_sql_to_php($row['ISBN']),
        'amount'=>persian_sql_to_php($row['Amount']), // <= if GoodMainCode is same key, I must sum it.
        'year_of_publish'=>persian_sql_to_php($row['SaleChap']),
        'period_print'=>persian_sql_to_php($row['NobateChap'])
    );


    array_push($mjson,$arr);

}



//added

foreach($mjson as $v){

    if(!isset($result[$v['GoodMainCode']]))
        $result[$v['GoodMainCode']] = $v;
    else
        $result[$v['GoodMainCode']]['amount'] += $v['amount'];
}

1 个答案:

答案 0 :(得分:2)

这应该适合你:

只需循环遍历您的数组并检查$result数组中是否包含来自$arr的当前内部数组字母的键。如果没有将它添加到$result数组并用数字初始化第二个键。

如果这个字母已经有一个键,你可以简单地在这个数组中添加数字。最后,我只需使用array_values()重新索引整个数组。

<?php

    foreach($arr as $v) {
        if(!isset($result[$v[0]]))
            $result[$v[0]] = $v;
        else
            $result[$v[0]][1] += $v[1];
    }

    $result = array_values($result);
    print_r($result);

?>

输出:

Array
(
    [0] => Array
        (
            [0] => A
            [1] => 35
        )
    //...
    [2] => Array
        (
            [0] => G
            [1] => 5
        )

)