2016-11-15 188 views
-1

我有解码的JSON响应问题:我不知道如何从PHP中的JSON解码数组中提取每个值。从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) 
      } 
     } 
    } 
} 

我要分析此数组中的每个值到变量,所以我可以与结果工作。

回答

0

注意var_dump没有返回值,所以,当你这样做:

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

...然后$json_responsenull

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

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

注意:不要叫你的变量$json_responcejson_decode后,因为那时它不再是JSON,但原生PHP数组。