API GET请求值不能在PHP中使用curljson_decode设置为变量和echo



为什么我不能在这个代码中回显$phone_number?上面写着

未定义的索引:phone_number。但当我回显$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;
?>

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

$responseData = json_decode($response, true);

然后您可以获得第一个电话号码(或通过更改数组索引获得的任何电话号码(:

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

您还可以循环浏览响应:

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

相关内容

最新更新