Merge array by key and sum another key

2019-03-04 02:08发布

I have this array and I need merge by key "name", also sum key "price", more in code example. Keys are static.

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
        )

)

Desired result :

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

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

Thank you very much

标签: php arrays sum key
1条回答
女痞
2楼-- · 2019-03-04 02:28

ok, I found it

    $items = array();
    foreach($prepare as $k=>$v) {
        if(!isset($items[$v['name']])) {
            $items[$v['name']] = $v;
        } else {
            $items[$v['name']]['price'] += $v['price'];
        }
    }
查看更多
登录 后发表回答