-1

I have order list in array; I'd like to have total quantity of articles ordered, so I need to remove remove duplicates id and get values of those id

I have this array

Array
(
    [0] => stdClass Object
        (
            [reservations_detail_article] => 100
            [reservations_detail_qte] => 10
        )

    [1] => stdClass Object
        (
            [reservations_detail_article] => 294
            [reservations_detail_qte] => 400
        )

    [2] => stdClass Object
        (
            [reservations_detail_article] => 294
            [reservations_detail_qte] => 30
        )

    [3] => stdClass Object
        (
            [reservations_detail_article] => 346
            [reservations_detail_qte] => 2
        )

)

and I would like to have

Array
(
    [0] => stdClass Object
        (
            [reservations_detail_article] => 100
            [reservations_detail_qte] => 10
        )

    [1] => stdClass Object
        (
            [reservations_detail_article] => 294
            [reservations_detail_qte] => 430
        )

    [2] => stdClass Object
        (
            [reservations_detail_article] => 346
            [reservations_detail_qte] => 2
        )



)

I already deleted dupluicates, but cannot have good total of quantity

2
  • Generally you have to try doing it before it will happen Commented Apr 26, 2017 at 17:07
  • Data is from Woocommerce orders so I cannot do it before, it's for reporting purposes Commented Apr 26, 2017 at 17:10

1 Answer 1

2

try this, it will check that this key already exit if exit then sum value .if array stdClass Object then

$result = array();
foreach ($data as $val) {
    if (!isset($result[$val->reservations_detail_article]))
        $result[$val->reservations_detail_article] = $val;
    else
        $result[$val->reservations_detail_article]['reservations_detail_qte'] += $val['reservations_detail_qte'];
}
$result = array_values($result); 
print_r($result);

if associative then

$result = array();
foreach ($data as $val) {
    if (!isset($result[$val['reservations_detail_article']]))
        $result[$val['reservations_detail_article']] = $val;
    else
        $result[$val['reservations_detail_article']]['reservations_detail_qte'] += $val['reservations_detail_qte'];
}
$result = array_values($result); 
print_r($result);
Sign up to request clarification or add additional context in comments.

1 Comment

Let's say that a second key must be matched besides "reservations_detail_article", like "reservations_detail_category". Can it be handled in this way too?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.