关联阵列计算

时间:2012-03-30 06:00:50

标签: php

我有这样的结果数组(如下)。

Array
(
    [10] => Array
        (
            [0] => Array
                (
                    [iPlannedCourseId] => 56
                    [fCreditHours] => 15.25
                )

            [1] => Array
                (
                    [iPlannedCourseId] => 57
                    [fCreditHours] => 14.50
                )

        )

    [11] => Array
        (
            [0] => Array
                (
                    [iPlannedCourseId] => 58
                    [fCreditHours] => 12.25
                )

            [1] => Array
                (
                    [iPlannedCourseId] => 59
                    [fCreditHours] => 14.75
                )

            [2] => Array
                (
                    [iPlannedCourseId] => 60
                    [fCreditHours] => 15.25
                )

        )

)

我希望按照父键对fCreditHours求和。有没有使用循环的功能 即,

Array 
(
        [10] = > 29.75
        [11] = > 42.25
)

2 个答案:

答案 0 :(得分:0)

您可以尝试使用array_walk()http://php.net/manual/en/function.array-walk.php

答案 1 :(得分:0)

您可以尝试使用array_walk_recursive和array_map组合。

我认为这对你很有用:

$a = array(100,300,
                    array(
                        2,
                        4,
                        ),
                        array(
                        13,
                        80,
                        ),
                        array(
                        40,
                50,
                        ),2.2,420,                        
                );


 $max = 0;

array_walk_recursive($a, 'arrmax');
function arrmax($item, $key) {
   global $max;
   $max = ($item > $max) ? $item : $max;

}
echo "Maximum Value is : " . $max;