Merge array by key and sum another key

2019-03-04 01:49发布

问题:

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

回答1:

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'];
        }
    }


标签: php arrays sum key