多维数组的最大值

时间:2014-08-14 06:15:00

标签: php arrays max

我有这个数组

  Array
(
    [2014-08-14] => Array
        (
            [18:00:00] => Array
                (
                    [6] => Array
                        (
                            [price] => 15.36
                            [avail_clean] => 5
                            [avail_noclean] => 6
                        )

                    [7] => Array
                        (
                            [price] => 17.35
                            [avail_clean] => 2
                            [avail_noclean] => 3
                        )

                )

            [19:00:00] => Array
                (
                    [6] => Array
                        (
                            [price] => 15.36
                            [avail_clean] => 5
                            [avail_noclean] => 6
                        )

                    [7] => Array
                        (
                            [price] => 17.35
                            [avail_clean] => 2
                            [avail_noclean] => 3
                        )

                )

        )

)

如何获得以下6& 7分别: - 价格总和 - 最大的avail_clean - 最大avail_noclean

我为此付出了代价:

foreach ($bookable as $date=>$key) {
    foreach ($key as $time=>$key2) {
        foreach($key2 as $room=>$key3){
            foreach($key3 as $price=>$key4){
                if($price == "price"){
                    if(isset($sumRoom[$room]['total'])){
                        $sumRoom[$room]['total'] += $key4;
                    }else{
                        $sumRoom[$room]['total'] = $key4;
                    }
                }
            }
        }

    }
}

给我这个

Array(
[6] => Array
    (
        [total] => 30,72
    )

[7] => Array
    (
        [total] => 34,7
    )

但是max(),我应该把它放在哪里?

1 个答案:

答案 0 :(得分:1)

foreach ($bookable as $date=>$times) {
    foreach ($times as $time=>$rooms) {
        foreach($rooms as $room=>$options){ $sumRoom[$room]['total'] = 0;
            foreach($options as $option=>$value){

                if($option == "price"){
                    $sumRoom[$room]['total'] += $value;
                }
                if($option == "avail_clean"){
                    $avail_clean[$room][] = $value;
                }
                if($option == "avail_noclean"){
                    $avail_noclean[$room][] = $value;
                }

            }
            $sumRoom[$room]['avail_clean_max'] = max($avail_clean[$room]);
            $sumRoom[$room]['avail_noclean'] = max($avail_noclean[$room]);
        }
    }
}

我已经编辑了我的答案..我已经合并了一个数组,即$sumRoom