如何从 cURL PHP 声明变量

How to declare variable from cURL PHP

我有一个 cURL 文件,它将 return 如下所示的数组,我想知道如何声明 [data]=>[id] 的变量。我试过 $decoded.data 或$decoded.[data] 但它不起作用。

Array
(
    [data] => Array
        (
            [id] => 2
            [email] => janet.weaver@reqres.in
            [first_name] => Janet
            [last_name] => Weaver
            [avatar] => https://reqres.in/img/faces/2-image.jpg
        )

    [support] => Array
        (
            [url] => https://reqres.in/#support-heading
            [text] => To keep ReqRes free, contributions towards server costs are appreciated!
        )

)

PHP 文件:

<?php
  $ch = curl_init();
  $url = "https://reqres.in/api/users/2";
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $resp = curl_exec($ch);
  $decoded = json_decode($resp,true);
  print_r($decoded);
  curl_close($ch);
?>
$decoded['data']
$decoded['data']['id']

是语法。但是端点必须 return 您用 json_encode()

打印的数组

I have an cURL file that will return an array like below

让我们分解一下您在这里要说的内容,并使用更清晰的术语来帮助您理解正在发生的事情。

  $ch = curl_init();
  $url = "https://reqres.in/api/users/2";
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $resp = curl_exec($ch);
  curl_close($ch); // you can call this straight away, you're done with $ch

这使用名为“curl”的库发出 HTTP 请求,并获取 响应正文$resp 中的值是一个字符串 - 不是文件,也不是任何 curl 甚至 HTTP 特定的东西,只是一个字符串。

$decoded = json_decode($resp,true);

这会获取字符串,并根据名为 JSON 的格式对其进行解析。将第二个参数设置为 true 表示您需要 PHP 数组,而不是数组和 stdClass 对象的混合体。假设没有错误,$decoded 现在是一个数组;不是 JSON 数组,只是一个常规的 PHP 数组。

print_r($decoded);

这就是您在问题中给出的输出。重要的是要理解这不是“数组”,它只是 一种显示它的方式 。其他方式包括 var_dump($decoded);var_export($decoded);.


那么,让我们改写你的第一句话:

I have a PHP array, which looks like this when displayed with print_r. (It's based on a JSON response I fetched using curl, but that's not really relevant right now.)


现在,回答您的问题:

how can I declare the variable of [data]=>[id]?

我想你想说的是我如何检索“[数据]=>[中显示的 ID]”。 (相信我,了解正确的术语将使您将来搜索和寻求帮助时的生活变得更加轻松。)

答案很简单:在 PHP 中,使用语法 $array['key'] 访问数组元素。因此 $decoded['data'] 访问 print_r 输出中 [data] => 中显示的所有内容,而 $decoded['data']['id'] 访问其中 [id] => 的内容。