简体   繁体   English

API GET 请求值无法设置为变量并使用 PHP 中的 curl json_decode 回显

[英]API GET request values cannot set to variables and echo using curl json_decode in PHP

Why can't I echo $phone_number in this code?为什么我不能在这段代码中回显 $phone_number? It says它说

Undefined index: phone_number.未定义索引:phone_number。 but when I echo $response it returns the values但是当我回显$response它返回值

    <?php

        $ch = curl_init( 'https://mighty-inlet-78383.herokuapp.com/api/hotels/imagedata');
        curl_setopt_array($ch, array(
            CURLOPT_RETURNTRANSFER => TRUE
        ));

        // Send the request
        $response = curl_exec($ch);

        // Check for errors
        if($response === FALSE){
            die(curl_error($ch));
            echo 'No responce';
        }

        // Decode the response
        $responseData = json_decode($response);

        // Print the date from the response
        $phone_number = $responseData['phone_number'];
        echo $phone_number;
   ?>

Because these are arrays within arrays you need to go one level deeper to get the data you want.因为这些是 arrays 中的 arrays,所以您需要深入 go 以获得所需的数据。 First, make sure you're returning the JSON as an array, using the 'true' attribute:首先,确保使用“true”属性将 JSON 作为数组返回:

$responseData = json_decode($response, true);

Then you can get the first phone number (or any phone number by changing the array index):然后你可以得到第一个电话号码(或通过改变数组索引的任何电话号码):

echo $responseData[0]['phone_number'];
echo $responseData[1]['phone_number'];

You can also loop through the responses:您还可以遍历响应:

foreach($responseData AS $response) {
    echo $response['phone_number'];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM