【问题标题】:Get specific values from CURL JSON response php array从 CURL JSON 响应 php 数组中获取特定值
【发布时间】: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 个元素的数组,其中是您的关联块。

标签: php arrays json curl


【解决方案1】:

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

$result[0]['first_name']

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

【讨论】:

  • 对不起,我不明白。 $result[0]['first_name'] 有效,但只会得到一个结果,即索引中的第一个结果。我需要在 foreach 循环中输出所有结果,但我只想要特定的,例如first_name 值。当我在 foreach 循环中使用它时 foreach ($result as $r) { echo $r['first_name']; }我得到空结果(没有显示)。
  • 这很奇怪。 foreach 肯定可以工作。我建议通过调试器运行它并检查值。
  • 原来这是一个未定义的索引错误,因为我之前有 $result['first_name']。这一直是我的问题。 foreach 循环现在工作。谢谢。
猜你喜欢
  • 1970-01-01
  • 2016-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多