0

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

Strogi
  • 33
  • 1
  • 6
  • Is this coming from a mysql server or has it some other source? Knowing this could give you more accurate answers. – Thaillie Sep 16 '15 at 22:50
  • Just asked 20 minutes ago: http://stackoverflow.com/q/32619813/3933332 and was also asked in another question today ... – Rizier123 Sep 16 '15 at 22:50
  • @Rizier123 to be fair, he is not just de-duping an array but also asking how to sum a value at the same time. And @OP, is this from a query? Because this could likely be done right in the query by grouping on the name and getting `sum(price)` as the column. Aside from that, have you tried to solve this yourself? Or are you just expecting someone to do it for you? – Jonathan Kuhn Sep 16 '15 at 22:55

1 Answers1

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'];
        }
    }
Strogi
  • 33
  • 1
  • 6