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

amrnrhlw  于 2022-11-13  发布在  PHP
关注(0)|答案(2)|浏览(182)

尝试从CURLJSON响应中回显几个值,这样我就可以将它们放入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 />';

我做错了什么?

suzh9iv8

suzh9iv81#

结果数组的嵌套深度为2。$result是数组的数组。因此:

$result[0]['first_name']

foreach ($result as $r) {
    echo $r['first_name'];
}
djp7away

djp7away2#

响应依赖于服务器回答你的请求,下面的工作完美地提取了访问令牌为例,你可以尝试下面的步骤来测试你所拥有的并提取你所需要的
之后

$response = curl_exec($ch);
 curl_close($ch);

我开始展示我所得到的
测试项目:

print_r ($response);

然后,转到提取(服务器响应的位置)头和正文,以使用其中的可用内容

list($header, $body) = explode("\r\n\r\n", $response, 2);

测试项目:

echo $header;
echo $body;

然后使用stdClass提取$body中项,以便在代码中使用

$bodyObject = json_decode($body);

测试项目:

print_r($bodyObject);

测试项目:

echo $bodyObject->access_token;

相关问题