【发布时间】:2016-03-09 14:32:55
【问题描述】:
尝试从 CURL JSON 响应中回显几个值,以便我可以将它们放入 foreach 循环中,但我只能让单个索引值起作用。
$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 decode 设置为 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 />';
我在这里做错了什么?
【问题讨论】:
-
$result[0]['first_name']是正确的。查看您的数组结构。否则,您可以设置$result = json_decode( $response, true )[0](在 php >= 5.5 上) -
有什么问题。您通过
$result[0]['first_name']获得价值,对吗?$result是一个包含 1 个元素的数组,其中是您的关联块。