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

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

为什么我不能在这段代码中回显 $phone_number?它说

Undefined index: phone_number. but when I echo $response it returns the values

    <?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;
   ?>

因为这些是数组中的数组,所以您需要更深入一层才能获得所需的数据。首先,确保使用 'true' 属性将 JSON 作为数组返回:

$responseData = json_decode($response, true);

然后你可以得到第一个phone数(或任何phone数通过改变数组索引):

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

您还可以遍历回复:

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