在数组php中遍历数组

时间:2018-07-20 15:38:00

标签: php

我有以下航班信息的输出。

    array(1) {
      ["ArrivedResult"]=>
      array(2) {
        ["next_offset"]=>
        int(10)
        ["arrivals"]=>
        array(10) {
          [0]=>
          array(10) {
            ["ident"]=>
            string(4) "SWA9"
            ["aircrafttype"]=>
            string(4) "B737"
            ["actualdeparturetime"]=>
            int(1532097153)
            ["actualarrivaltime"]=>
            int(1532100120)
            ["origin"]=>
            string(4) "KDAL"
            ["destination"]=>
            string(4) "KHOU"
            ["originName"]=>
            string(17) "Dallas Love Field"
            ["originCity"]=>
            string(10) "Dallas, TX"
            ["destinationName"]=>
            string(15) "William P Hobby"
            ["destinationCity"]=>
            string(11) "Houston, TX"
          }

我正在尝试访问数据目标,我已经尝试过使用以下代码

        foreach ($coded_json['DepartedResult']['departures'] as $key => $value) {
            echo $value;
        }

我收到以下错误

  

注意:数组到字符串的转换

3 个答案:

答案 0 :(得分:1)

如果您的问题中的departuresarrivals,则它是一个关联数组的二维数组。您需要访问destination属性。

foreach ($coded_json['DepartedResult']['departures'] as $key => $value) {
    echo $value['destination'] . '<br>';
}

答案 1 :(得分:0)

从您的代码中,我了解到您想要迭代数组,所以这里是我测试过的有效代码

$coded_json = array(
                    "DepartedResult" => array("next_offset"=>10,
                    "departures"=>array(array("ident"=>"SWA9",
                                        "aircrafttype"=>"B737",
                                        "actualdeparturetime"=>1532097153,
                                        "actualarrivaltime"=>1532100120,
                                        "origin"=>"KDAL",
                                        "destination"=>"KHOU",
                                        "originName"=>"Dallas Love Field",
                                        "originCity"=>"Dallas, TX",
                                        "destinationName"=>"William P Hobby",
                                        "destinationCity"=>"Houston, TX",
                                  ))));

foreach ($coded_json['DepartedResult'][0]['departures'] as $key => $value) {
    echo '<br/>'.$value;
}

输出

SWA9
B737
1532097153
1532100120
KDAL
KHOU
Dallas Love Field
Dallas, TX
William P Hobby
Houston, TX

您可以按以下方式访问目的地

echo $coded_json['DepartedResult']['departures'][0]['destination'];

答案 2 :(得分:0)

foreach($coded_json["ArrivedResult"]["arrivals"] as $foo){
    var_dump($foo['destination']);
}