【问题标题】:Basic JSON Decode foreach loop not working php基本JSON解码foreach循环不起作用php
【发布时间】:2019-01-05 18:23:31
【问题描述】:

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

【问题讨论】:

  • 添加json数据。提问。
  • 这些答案都没有解决您的问题吗?

标签: php arrays json curl


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    $json['results'][0]['geometry'] 在 JSON 中是一个对象,而不是一个数组。当你转换它时,你会得到一个带有键'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
                   )
           )
    

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

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

    【讨论】:

      【解决方案3】:

      请先做 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)

      【讨论】:

        【解决方案4】:

        试试这个,它在这里工作 您的代码不起作用,因为您的第一个 foreach 循环将循环一次,因为 $json['results'] 只有一个索引 0,而第二个 foreach 循环将循环三次,因为 $item['geometry'] 有三个索引(位置,location_type,视口)。在第二个 foreach 循环中,您的 $item2 变量将包含来自 (location,location_type,viewport) 的每个索引的值,这意味着您将在此 $item2 变量中获得“纬度”索引。您不需要运行第三个 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);
        
        ?>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多