从数组中删除重复并添加其对应的值

时间:2015-03-04 10:58:21

标签: php arrays

  

我有一个关联数组。下面给出了

Array
(
[0] => Array
    (
        [amount] => 99
        [email] => test@gmail.com

    )

[1] => Array
    (
        [amount] => 5.10
        [email] => test@gmail.com

    )

)

我想从数组中删除重复的电子邮件,并将其金额添加到相应的电子邮件中。我试过php函数array_unique(),但它只给我一些数据。

我当前的输出是

Array
    (
        [amount] => 99
        [email] => test@gmail.com

    )

但我希望输出像

 Array
    (
        [amount] => 104.1
        [email] => test@gmail.com

    )

1 个答案:

答案 0 :(得分:0)

你可以做什么:

$arr = array(
    array('amount' => 99, 'email' => 'test@gmail.com'),
    array('amount' => 5.10, 'email' => 'test@gmail.com')
);

$res = array();

foreach ($arr as $bill) {
    if (!isset($res[$bill['email']])) {
        $res[$bill['email']] = 0;
    }

    $res[$bill['email']] += $bill['amount'];
}

// if you want the same output, format the array back to original:
$arr = array();
foreach ($res as $mail => $amount) {
    $arr[] = array('mail' => $mail, 'amount' => $amount);
}
unset($res);
var_dump($arr);

这给了你:

array(1) {
  [0]=>
  array(2) {
    ["mail"]=>
    string(14) "test@gmail.com"
    ["amount"]=>
    float(104.1)
  }
}

您可以在此处查看并测试:http://ideone.com/u6tAYv