如何正确地将字符串转换为 PHP 中的关联数组

How to Properly Convert String to Associative Array in PHP

我想将此字符串转换为适当的关联数组。

请点击 link 查看字符串数据。

https://maps.googleapis.com/maps/api/geocode/json?latlng=16.539311299999998,80.5820222

我希望将其转换为适当的 Associaitve 数组。

我看起来像这样。

echo $array['long_name'] 应该 return 像 'Attlee Road'

这样的值

请帮我解决这个问题,我从 2 天开始尝试这个,尝试所有爆炸、内爆、foreach 循环,我很困惑,请有人帮我解决这个问题。

下面的代码将回显字符串数据

<?php

$lat = 16.539311299999998;
$lng = 80.5820222;

$url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" . $lat . "," . $lng . ";

function get_data($url) {
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

$returned_contents = get_data($url);

echo "<pre>";
print_r($returned_contents);
echo "</pre>";

?>

在输出中使用 json_decode()

您必须使用 json_decode() 功能。

<?php

$lat = 16.539311299999998;
$lng = 80.5820222;

$url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" . $lat . "," . $lng . "&key=AIzaSyDCgyjLTrpadabEAyDNXf2GPpgChvpMw_4";

function get_data($url) {
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

$returned_contents = get_data($url);

$returned_contents_array = json_decode($returned_contents, true);
$results = $returned_contents_array['results'];
foreach($results as $result) {
    echo $result['address_components'][0]['long_name'];
}

?>

试一试

<?php

$lat = 16.539311299999998;
$lng = 80.5820222;

$url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" . $lat . "," . $lng . "&key=AIzaSyDCgyjLTrpadabEAyDNXf2GPpgChvpMw_4";

function get_data($url) {
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

$returned_contents = get_data($url);
$returned_contents = json_decode($returned_contents);
echo "<pre>";
print_r($returned_contents);
echo "</pre>";

?>