【问题标题】:Extract values from JSON array从 JSON 数组中提取值
【发布时间】:2016-11-15 12:56:28
【问题描述】:

我在解码 JSON 响应时遇到问题:我不知道如何从 PHP 中的 JSON 解码数组中提取每个值。

我的脚本是这样的:

$adresse= $_POST['address'];
$url = 'http://my/host/folder/api';
$data = array(
    "value" => $adresse,
);
$data_string = json_encode($data);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "some_user:somepassword");
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER,
               array('Content-Type:application/json',
                     'Content-Length: ' . strlen($data_string))
               );
$resp = curl_exec($ch);
curl_close($ch);
$json_response = var_dump(json_decode($resp, true));
echo 'test = '.$json_response[1]['zipcode'];

这段代码返回一个像这样的数组:

array(1) { 
    ["eligibilities"]=> array(1) { 
        [0]=> array(2) { 
            ["address"]=> array(5) { 
                ["zipcode"]=> string(5) "60000" 
                ["city"]=> string(9) "SomeCITY" 
                ["streetName"]=> string(17) "SomeSTreetName" 
                ["streetNumber"]=> string(2) "17" 
                ["idRA"]=> string(10) "SomeIDRA"
            }
            ["broadBand"]=> array(5) { 
                ["eligible"]=> bool(true) 
                ["type"]=> string(10) "SomeType" 
                ["maxDownstream"]=> int(20000) 
                ["maxUpstream"]=> int(1000) 
                ["tvEligible"]=> bool(false) 
            }
        }
    }
}

我想将此数组中的每个值解析为变量,以便处理结果。

【问题讨论】:

    标签: php json parsing curl decode


    【解决方案1】:

    注意var_dump 不返回值,所以当你这样做时:

    $json_response = var_dump(json_decode($resp, true));
    

    ...那么$json_response 将是null。

    要访问这些内部值,请不要忘记您的数据中涉及多个嵌套级别,并且您需要提及每个级别的键。这样做:

    $result = json_decode($resp, true);
    var_dump($result);
    echo 'test = ' . $result['eligibilities'][0]['address']['zipcode'];
    

    注意:不要在json_decode 之后调用变量$json_responce,因为那样它就不再是 JSON,而是原生 PHP 数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-11
      • 2018-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-08
      • 1970-01-01
      • 2021-05-06
      相关资源
      最近更新 更多