二维关联数组中类似元素的总和 - PHP

时间:2012-09-04 05:04:37

标签: php multidimensional-array foreach associative-array

我有一个如下所示的数组

Array (
        [0]=> Array
                (
                   [employee_num]  =>1009
                   [employee_name] =>Jane Doe
                   [amount]        =>4500.00
                )
        [1]=> Array
                (
                   [employee_num]  =>1009
                   [employee_name] =>Jane Doe
                   [amount]        =>2500.00
                )
        [2]=> Array
                (
                   [employee_num]  =>1033
                   [employee_name] =>Test User
                   [amount]        =>3455.50
                )
        [3]=> Array
                (
                   [employee_num]  =>1009
                   [employee_name] =>Jane Doe
                   [amount]        =>5500.00
                )
        [4]=> Array
                (
                   [employee_num]  =>1033
                   [employee_name] =>Test User
                   [amount]        =>7500.00
                )
     )

我想得到的是如下数组: (每个用户一个条目,金额值总和。)我知道我必须使用for-each,但不能真正理解如何合并[employee_num]和[employee_name]的条目。我事先并不知道数组中类似条目或其索引的数量。

Array (
        [0]=> Array
                (
                   [employee_num]  =>1009
                   [employee_name] =>Jane Doe
                   [amount]        =>12500.00
                )
        [1]=> Array
                (
                   [employee_num]  =>1033
                   [employee_name] =>Test User
                   [amount]        =>10955.50
                )
      )

我该怎么做?有人可以帮忙吗?感谢。

2 个答案:

答案 0 :(得分:1)

function sumAmount($data)
{
    $rst=array();
    foreach($data as $info)
    {
        if(!isset($rst[$info["employee_num"]]))
            $rst[$info["employee_num"]]=$info;
        else
            $rst[$info["employee_num"]]["amount"]+=$info["amount"];
    }
    return array_values($rst);
}

答案 1 :(得分:0)

假设$ array是原始数组:

$outputArray = array();
foreach ($array as $employeeArray) {
    $outputArray[$employeeArray['employee_name']]['employee_num'] = $employeeArray['employee_num'];
    $outputArray[$employeeArray['employee_name']]['employee_name'] = $employeeArray['employee_name'];
    $outputArray[$employeeArray['employee_name']]['amount'] += $employeeArray['amount'];
}
print_r($outputArray);

$outputArray的键将是员工的姓名。如果您想通过employee_num进行匹配,只需使用$outputArray[$employeeArray['employee_num']]代替$outputArray[$employeeArray['employee_name']]