对具有不可预测键的多维数组求和

时间:2013-04-12 09:09:01

标签: php arrays sum

我有这个多维数组(如果这就是所谓的)客户和客户内部是他的物品,以及这些物品的费用..但是,我需要从物品中获得所有费用并为客户总结。 数组结构

    Array
    (
        [6bb728] => Array
            (
                [TitleName] => Sir Isaac
                [Surname] => Newton
                [sum] =>
                [id] => 6bb728
                [items] => Array
                    (
                        [29] => Array
                            (
                                [AssignedTo] => 6bb728
                                [Number] => 03-014
                                [MFee] => 103.5
                            )

                    )

            )

总和密钥应包含项目费用的总和。这让我想到了一个问题:是否有任何有效的方法来获得多维数组中存在的一个键的总和?

我尝试了一个四倍的foreach,它将我的计算机送入循环(有数百个客户,它必须做很多循环)

foreach($customers as $value) {
    foreach($value as $value1){
        foreach($value1['items'] as $value2) {
            foreach($value2 as $value3) {
                $customers[$value3['AssignedTo']]['Fee'] += $value3['MFee'];
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

看起来你可以把它减少到:

foreach($customers as $customer) {
    foreach($customer['items'] as $item) {
        $customers[$item['AssignedTo']]['Fee'] += $item['MFee'];
    }
}

编辑:实际上您也可以让这项任务更容易混淆:

$customer['Fee'] += $item['MFee'];

答案 1 :(得分:0)

在循环客户时使用multiple loops而不是嵌套循环。

例如:

<?php
$input_array = array('a' => 'aaa', 'b' => 'bbb', 'c' => 'ccc', 'd' => 'dddd', 'e' => 'eeee');

//chunks of size 2
$my_array_chunks = array_chunk($input_array, count($input_array) / 2, true);
?>

//数组块形成

Array
(
  [0] => Array
        (
            [a] => aaa
            [b] => bbb
        )

    [1] => Array
        (
            [c] => ccc
            [d] => dddd
        )

    [2] => Array
        (
            [e] => eeee
        )

)

划分多个循环

<?php
foreach(my_array_chunks[0] as $val){
   //code here
}
foreach(my_array_chunks[1] as $val){
      //code here
}

foreach(my_array_chunks[2] as $val){
     //code here
}

Why is one loop so much slower than two loops?