如何输出此数组?

时间:2019-11-12 03:16:00

标签: php multidimensional-array foreach

$weatherData = [
    "Chicago" => [45, "fog",   ["Mon" => [44, "fog"], "Tue" => [42, "sleet"], "Wed" => [40, "rain"], "Thu" => [44, "cloudy"], "Fri" => [45, "cloudy"]]],
    "Paris" =>   [73, "sunny", ["Mon" => [75, "sunny"], "Tue" => [75, "sunny"], "Wed" => [68, "cloudy"], "Thu" => [66, "cloudy"], "Fri" => [60, "rain"]]],
    "Calgary" => [-8, "snow",  ["Mon" => [-7, "snow"], "Tue" => [-10, "snow"], "Wed" => [-3, "sleet"], "Thu" => [0, "cloudy"], "Fri" => [3, "sunny"]]]
];

比方说,我想有一个foreach循环来输出“周一至周五”数据,我该怎么做?这是我的尝试,只显示每个城市的星期一数组的第一个数字(“ 44,75,-7”):

foreach($weatherData as $w){
        echo $w["Mon"][0]
}

请帮助谢谢!

1 个答案:

答案 0 :(得分:0)

<?php

$weatherData = [
    "Chicago" => [45, "fog",   ["Mon" => [44, "fog"], "Tue" => [42, "sleet"], "Wed" => [40, "rain"], "Thu" => [44, "cloudy"], "Fri" => [45, "cloudy"]]],
    "Paris" =>   [73, "sunny", ["Mon" => [75, "sunny"], "Tue" => [75, "sunny"], "Wed" => [68, "cloudy"], "Thu" => [66, "cloudy"], "Fri" => [60, "rain"]]],
    "Calgary" => [-8, "snow",  ["Mon" => [-7, "snow"], "Tue" => [-10, "snow"], "Wed" => [-3, "sleet"], "Thu" => [0, "cloudy"], "Fri" => [3, "sunny"]]]
];

foreach ($weatherData as $cityName => $weatherArrArr) {
    $weekWeatherArr = $weatherArrArr[2];

    foreach ($weekWeatherArr as $dayName => $weatherArr) {
        $temp = $weatherArr[0];
        $comment = $weatherArr[1];
        echo $cityName . "'s weather for " . $dayName . ' is: ' . $comment . ' ' . $temp . '<br>' . PHP_EOL;
    }
}

给出结果:

Chicago's weather for Mon is: fog 44<br>
Chicago's weather for Tue is: sleet 42<br>
Chicago's weather for Wed is: rain 40<br>
Chicago's weather for Thu is: cloudy 44<br>
Chicago's weather for Fri is: cloudy 45<br>
Paris's weather for Mon is: sunny 75<br>
Paris's weather for Tue is: sunny 75<br>
Paris's weather for Wed is: cloudy 68<br>
Paris's weather for Thu is: cloudy 66<br>
Paris's weather for Fri is: rain 60<br>
Calgary's weather for Mon is: snow -7<br>
Calgary's weather for Tue is: snow -10<br>
Calgary's weather for Wed is: sleet -3<br>
Calgary's weather for Thu is: cloudy 0<br>
Calgary's weather for Fri is: sunny 3<br>
相关问题