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

时间:2018-07-29 07:09:00

标签: php arrays json curl

已经花了很长时间了,我为为什么使用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'];起作用?如果有人可以帮助我理解为什么会这样,那就太好了!

4 个答案:

答案 0 :(得分:0)

仅查看从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"
}

答案 1 :(得分:0)

JSON中的

RuntimeError: cuda runtime error (2) : out of memory at /opt/conda/conda-bld/pytorch_1525909934016/work/aten/src/THC/generic/THCStorage.cu:58是一个对象,而不是数组。转换时,您会得到一个包含键“ location”,“ location_type”和“ viewport”的数组:

$json['results'][0]['geometry']

[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 ) ) 上的foreach失败。

但是,您可以直接访问$item2['location']或使用代码$json['results'][0]['geometry']['location']['lat']

答案 2 :(得分:0)

请首先执行var_dump:

>>> while True:
...     number = input('please input a number:')
...     print(number)
...
please input a number:1
1
please input a number:2
2
please input a number:3
3
please input a number:4
4
......

var_dump结果是:

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

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

    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"
    }
  }
}

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

答案 3 :(得分:0)

尝试一下,它在这里工作 您的代码不起作用,因为您的第一个foreach循环将循环执行一次,因为$ json ['results']仅具有一个索引0,而第二个foreach循环将循环进行三次,因为$ item ['geometry']具有三个索引(位置,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);

?>