PHP总和特定键由2个其他人排序

时间:2012-09-10 23:55:07

标签: php arrays

我想只加1个键,但按其他2键排序:

<?php
Array
(
    [0] => Array
        (
            [week] => 1
            [info] => a
            [hours] => 4
        )

    [1] => Array
        (
            [week] => 2
            [info] => a
            [hours] => 4
        )

    [2] => Array
        (
            [week] => 2
            [info] => a
            [hours] => 4
        )
    [3] => Array
        (
            [week] => 2
            [info] => b
            [hours] => 4
        )
    [4] => Array
        (
            [week] => 2
            [info] => c
            [hours] => 4
        )
    [5] => Array
        (
            [week] => 3
            [info] => b
            [hours] => 4
        )
    [6] => Array
        (
            [week] => 3
            [info] => b
            [hours] => 4
        )
)
?>

我想将按小时排序的小时数相加。每周都有自己的信息。 首先,我想总结每个信息的小时数,然后按周对它们进行排序。

示例:

week:1  info:a   hours:4
week:2  info:a   hours:8
week:2  info:b   hours:4
week:2  info:c   hours:4
week:3  info:b   hours:8

如何做到这一点?

1 个答案:

答案 0 :(得分:1)

您只需要重新排列数组:

$todisplay = array();
foreach ($weeks as $week) {
   //Does not properly check for set keys; you should do isset checks
   $todisplay[$week['week']][$week['info']] += $week['hours'];
}
ksort($todisplay);

然后你可以迭代todisplay来构建表。