2016-11-15 113 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數組。