首页 > 解决方案 > 如何在 laravel dd 函数中访问特定的数组值

问题描述

我只需要基于我在参数中输入的地址的地理位置坐标。我正在使用 curl 的请求。

这是我的卷曲请求

        $url = 'https://maps.googleapis.com/maps/api/geocode/json?address=10%20BISHAN%STREET%2013&key='.$key;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $response = json_decode(curl_exec($ch), true);
        dd($response);

我得到了回应

array:2 [▼
  "results" => array:1 [▼
    0 => array:6 [▼
      "address_components" => array:6 [▶]
      "formatted_address" => "10 Bishan Street 13, Singapore 579795"
      "geometry" => array:3 [▼
        "location" => array:2 [▼
          "lat" => 1.349774
          "lng" => 103.854975
        ]
        "location_type" => "ROOFTOP"
        "viewport" => array:2 [▶]
      ]
      "place_id" => "ChIJR0tGixEX2jERVE4uZWfBN-o"
      "plus_code" => array:2 [▶]
      "types" => array:1 [▶]
    ]
  ]
  "status" => "OK"
]

如果我做dd($response['result']);

我明白了

  0 => array:6 [▼
    "address_components" => array:6 [▶]
    "formatted_address" => "10 Bishan Street 13, Singapore 579795"
    "geometry" => array:3 [▼
      "location" => array:2 [▼
        "lat" => 1.349774
        "lng" => 103.854975
      ]
      "location_type" => "ROOFTOP"
      "viewport" => array:2 [▼
        "northeast" => array:2 [▼
          "lat" => 1.3511229802915
          "lng" => 103.85632398029
        ]
        "southwest" => array:2 [▼
          "lat" => 1.3484250197085
          "lng" => 103.85362601971
        ]
      ]
    ]
    "place_id" => "ChIJR0tGixEX2jERVE4uZWfBN-o"
    "plus_code" => array:2 [▼
      "compound_code" => "8VX3+WX Singapore"
      "global_code" => "6PH58VX3+WX"
    ]
    "types" => array:1 [▼
      0 => "street_address"
    ]
  ]
]

有没有办法我可以location直接使用dd?感谢您的回答。

标签: phparraysjsonlaravel

解决方案


如果您遵循层次结构,您只需在每个阶段添加相应的数组元素名称,这应该会给您...

$response['result'][0]['geometry']['location']

如果有更多结果,[0]可能需要 a 。foreach


推荐阅读