从JSON数组中提取值

时间:2016-11-15 12:56:29

标签: php json parsing curl decode

我遇到解码的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) 
            }
        }
    }
}

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

1 个答案:

答案 0 :(得分:0)

请注意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_responce之后调用变量json_decode,因为它不再是JSON,而是本机PHP数组。