php从数组中删除重复项和它们的总和

时间:2017-04-26 17:07:11

标签: php arrays

我在数组中有订单列表;我想订购总数量的文章,所以我需要删除删除重复ID并获取这些ID的值

我有这个数组

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
        )

)

我希望

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
        )



)

我已经删除了dupluicates,但不能有很好的数量

1 个答案:

答案 0 :(得分:0)

试试这个,它会检查这个键是否已退出,如果退出然后总和值.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);

如果是关联的那么

$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);