0

我有一个如下所示的数组

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

我怎样才能做到这一点?任何人都可以帮忙吗?谢谢。

4

2 回答 2

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);
}
于 2012-09-04T05:11:54.057 回答
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']].

于 2012-09-04T05:11:32.933 回答