按键合并数组并加总另一个键

时间:2015-09-16 22:43:25

标签: php arrays sum key

我有这个数组,我需要通过键“name”进行合并,也需要和键“价格”,在代码示例中更多。键是静态的。

Array
(
    [0] => Array
        (
            [name] => Sapiente quo incidunt nostrum dolore
            [price] => 50
        )

    [1] => Array
        (
            [name] => Global Donation
            [price] => 10
        )

    [2] => Array
        (
            [name] => Global Donation
            [price] => 10
        )

)

期望的结果:

Array
(
    [0] => Array
        (
            [name] => Sapiente quo incidunt nostrum dolore
            [price] => 50
        )

    [1] => Array
        (
            [name] => Global Donation
            [price] => 20
        )
)

非常感谢

1 个答案:

答案 0 :(得分:1)

好的,我找到了

    $items = array();
    foreach($prepare as $k=>$v) {
        if(!isset($items[$v['name']])) {
            $items[$v['name']] = $v;
        } else {
            $items[$v['name']]['price'] += $v['price'];
        }
    }