嘗試從CURL JSON響應中回顯兩個值,因此我可以將它們放入foreach循環中,但我只能獲取單個索引值才能工作。從CURL JSON響應php數組獲取特定值
$request = curl_init($api); // initiate curl object
curl_setopt($request, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response
curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
//curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment if you get no gateway response and are using HTTPS
curl_setopt($request, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($request, CURLOPT_HTTPHEADER, array(
"Content-Type: application/x-www-form-urlencoded"
));
$response = (string)curl_exec($request); // execute curl fetch and store results in $response
curl_close($request); // close curl object
$result = json_decode($response, true); // true turns it into an array
echo 'First Name: ' . $result['first_name'] . '<br />'; // why doesnt this work
echo 'Last Name: ' . $result[0]['last_name'] . '<br />'; // yet i can return the first value
例陣列輸出
Array
(
[0] => Array
(
[id] => 34761
[first_name] => A
[last_name] => Bailes
[clinic] =>
[phone] => 7409923279
[fax] => 7409926740
[address1] => 507 Mulberry Heights Rd
[address2] =>
[city] => Pomeroy
[subdivision] => OH
[country_code] =>
[postal_code] => 45769-9573
[timezone] => Array
(
[timezone_type] => 3
[timezone] => America/New_York
)
[state] => OH
)
)
我有JSON解碼設置爲true陣列輸出
$result = json_decode($response, true); // true turns it into an array
但是當我嘗試來呼應 '如first_name' 值它只返回空。
echo 'First Name: ' . $result['first_name'] . '<br />'; // why doesnt this work
但我可以返回一個索引值
echo 'First Name: ' . $result[0]['first_name'] . '<br />';
我到底做錯了什麼?
'$結果[0] [ 'FIRST_NAME']'是正確的。查看你的數組結構。否則,你可以設置'$ result = json_decode($ response,true)[0]'(在php> = 5.5) – fusion3k
有什麼問題。你正在通過'$ result [0] ['first_name']'獲得值? '$ result'是一個包含1個元素的數組,其中是您的關聯塊。 – LightNight