从CURL JSON响应php数组中获取特定值

时间:2016-03-09 14:32:55

标签: php arrays json curl

尝试从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 />';

我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

您的结果数组嵌套2深。 $result是一个数组数组。所以:

$result[0]['first_name']

foreach ($result as $r) {
    echo $r['first_name'];
}
相关问题