繁体   English   中英

基本JSON解码foreach循环无法正常工作php

[英]Basic JSON Decode foreach loop not working php

已经花了相当长的时间了,我为为什么使用foreach循环不起作用而我展示的另一种方法起作用感到困惑。

我的代码:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://maps.googleapis.com/maps/api/geocode/json?address=1%20The%20Strand%20Wellard");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json"
));

$response = curl_exec($ch);

$json = json_decode($response, true);

foreach ($json['results'] as $item) {
  foreach ($item['geometry'] as $item2) {
    foreach ($item2['location'] as $item3) {
      echo $item3['lat'];
    }
  }
  echo $item['geometry']['location']['lat'];
}

curl_close($ch);

JSON数据: https//pastebin.com/JU1wSpsD

为什么不echo $item3['lat']; 工作,但echo $item['geometry']['location']['lat']; 工作吗? 如果有人可以帮助我理解为什么会这样,那太好了!

只需查看您从curl请求中获取的json,就可以尝试迭代非多维的几何。

如果几何像

"geometry": [{
        "location": {
          "lat": -32.2630411,
          "lng": 115.8164093
        }],

可以重复,但是可以像这样直接访问您收到的格式。

"geometry": {
            "location": {
              "lat": -32.2630411,
              "lng": 115.8164093
            },
foreach ($json['results'] as $item) {

  echo $item['geometry']['location']['lat'];
  echo $item['geometry']['location']['lng'];
} 

下面是从curl获得的json。

{
  "results": [
    {
      "address_components": [
        {
          "long_name": "1",
          "short_name": "1",
          "types": [
            "street_number"
          ]
        },
        {
          "long_name": "The Strand",
          "short_name": "The Strand",
          "types": [
            "route"
          ]
        },
        {
          "long_name": "Wellard",
          "short_name": "Wellard",
          "types": [
            "locality",
            "political"
          ]
        },
        {
          "long_name": "City of Kwinana",
          "short_name": "Kwinana",
          "types": [
            "administrative_area_level_2",
            "political"
          ]
        },
        {
          "long_name": "Western Australia",
          "short_name": "WA",
          "types": [
            "administrative_area_level_1",
            "political"
          ]
        },
        {
          "long_name": "Australia",
          "short_name": "AU",
          "types": [
            "country",
            "political"
          ]
        },
        {
          "long_name": "6170",
          "short_name": "6170",
          "types": [
            "postal_code"
          ]
        }
      ],
      "formatted_address": "1 The Strand, Wellard WA 6170, Australia",
      "geometry": {
        "location": {
          "lat": -32.2630411,
          "lng": 115.8164093
        },
        "location_type": "ROOFTOP",
        "viewport": {
          "northeast": {
            "lat": -32.2616921197085,
            "lng": 115.8177582802915
          },
          "southwest": {
            "lat": -32.2643900802915,
            "lng": 115.8150603197085
          }
        }
      },
      "place_id": "ChIJTTGvZi2FMioReYR3OgBb-p4",
      "plus_code": {
        "compound_code": "PRP8+QH Wellard, Western Australia, Australia",
        "global_code": "4PVQPRP8+QH"
      },
      "types": [
        "street_address"
      ]
    }
  ],
  "status": "OK"
}

$json['results'][0]['geometry']是一个对象,而不是数组。 转换时,将得到一个包含键“ location”,“ location_type”和“ viewport”的数组:

[geometry] => Array
      (
          [location] => Array
               (
                    [lat] => -32.2630411
                    [lng] => 115.8164093
                )
          [location_type] => ROOFTOP
          [viewport] => Array
              (
                   [northeast] => Array
                       (
                           [lat] => -32.261692119708
                           [lng] => 115.81775828029
                       )
                    [southwest] => Array
                       (
                           [lat] => -32.264390080291
                           [lng] => 115.81506031971
                       )
               )
        )

然后$item2依次变成那些值,即

Array
    (
         [lat] => -32.2630411
         [lng] => 115.8164093
    )

然后

'ROOFTOP'

然后

Array
    (
         [northeast] => Array
              (
                   [lat] => -32.261692119708
                   [lng] => 115.81775828029
               )
          [southwest] => Array
               (
                   [lat] => -32.264390080291
                   [lng] => 115.81506031971
               )
       )

如您所见,这些数组都没有键“ location”,因此$item2['location']上的foreach失败。

但是,您可以直接访问$json['results'][0]['geometry']['location']['lat']或在您的代码$item['geometry']['location']['lat']

请先做var_dump:

echo '<pre style="direction:ltr">';
var_dump($json['results']);
die();

var_dump结果为:

    array(1) {
  [0]=>
  array(6) {
    ["address_components"]=>
    array(7) {
      [0]=>
      array(3) {
        ["long_name"]=>
        string(1) "1"
        ["short_name"]=>
        string(1) "1"
        ["types"]=>
        array(1) {
          [0]=>
          string(13) "street_number"
        }
      }
      [1]=>
      array(3) {
        ["long_name"]=>
        string(10) "The Strand"
        ["short_name"]=>
        string(10) "The Strand"
        ["types"]=>
        array(1) {
          [0]=>
          string(5) "route"
        }
      }
      [2]=>
      array(3) {
        ["long_name"]=>
        string(7) "Wellard"
        ["short_name"]=>
        string(7) "Wellard"
        ["types"]=>
        array(2) {
          [0]=>
          string(8) "locality"
          [1]=>
          string(9) "political"
        }
      }
      [3]=>
      array(3) {
        ["long_name"]=>
        string(15) "City of Kwinana"
        ["short_name"]=>
        string(7) "Kwinana"
        ["types"]=>
        array(2) {
          [0]=>
          string(27) "administrative_area_level_2"
          [1]=>
          string(9) "political"
        }
      }
      [4]=>
      array(3) {
        ["long_name"]=>
        string(17) "Western Australia"
        ["short_name"]=>
        string(2) "WA"
        ["types"]=>
        array(2) {
          [0]=>
          string(27) "administrative_area_level_1"
          [1]=>
          string(9) "political"
        }
      }
      [5]=>
      array(3) {
        ["long_name"]=>
        string(9) "Australia"
        ["short_name"]=>
        string(2) "AU"
        ["types"]=>
        array(2) {
          [0]=>
          string(7) "country"
          [1]=>
          string(9) "political"
        }
      }
      [6]=>
      array(3) {
        ["long_name"]=>
        string(4) "6170"
        ["short_name"]=>
        string(4) "6170"
        ["types"]=>
        array(1) {
          [0]=>
          string(11) "postal_code"
        }
      }
    }
    ["formatted_address"]=>
    string(40) "1 The Strand, Wellard WA 6170, Australia"
    ["geometry"]=>
    array(3) {
      ["location"]=>
      array(2) {
        ["lat"]=>
        float(-32.2630411)
        ["lng"]=>
        float(115.8164093)
      }
      ["location_type"]=>
      string(7) "ROOFTOP"
      ["viewport"]=>
      array(2) {
        ["northeast"]=>
        array(2) {
          ["lat"]=>
          float(-32.2616921197085)
          ["lng"]=>
          float(115.8177582802915)
        }
        ["southwest"]=>
        array(2) {
          ["lat"]=>
          float(-32.2643900802915)
          ["lng"]=>
          float(115.8150603197085)
        }
      }
    }
    ["place_id"]=>
    string(27) "ChIJTTGvZi2FMioReYR3OgBb-p4"
    ["plus_code"]=>
    array(2) {
      ["compound_code"]=>
      string(45) "PRP8+QH Wellard, Western Australia, Australia"
      ["global_code"]=>
      string(11) "4PVQPRP8+QH"
    }
    ["types"]=>
    array(1) {
      [0]=>
      string(14) "street_address"
    }
  }
}

您必须从结果中获取索引0:

    echo '<pre style="direction:ltr">';
    var_dump($json['results'][0]['geometry']   ['location']['lat']);
    die();

结果是: float(-32.2630411)

试试这个,它在这里工作您的代码不起作用,因为您的第一个foreach循环将循环一次,因为$ json ['results']仅具有一个索引0,而第二个foreach循环将循环通过三倍,而$ item ['几何]]具有三个索引(位置,location_type,视口)。 在第二个foreach循环中,您的$ item2变量将包含(location,location_type,viewport)中每个索引的值,这意味着您将在此$ item2变量中获得“ lat”索引。 您无需运行第三个foreach循环:)

    <?php 
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://maps.googleapis.com/maps/api/geocode/json?address=1%20The%20Strand%20Wellard");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json"
));

$response = curl_exec($ch);

$json = json_decode($response, true);


foreach ($json['results'] as $item) {

  foreach ($item['geometry'] as $key=>$item2) {

   if($key == 'location')
    echo $item2['lat'];

    }

}

curl_close($ch);

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM