如何使用 if-else 语句在 php foreach 中获取对象 json?
How to get object json in php foreach with if-else statement?
我想设置图像但在第 8 行出现错误
<?php
$url = "https://dog.ceo/api/breeds/image/random";
$json = file_get_content($url);
$obj = json_decode($json, TRUE);
foreach($obj as $key) if
(
echo <img src='$key['message']'/>
else
echo <img src='not_found.png'/>
);
?>
有什么解决办法?
您不需要 foreach
循环作为 api returns 常规 json。也许你想得到这样的结果。
$url = "https://dog.ceo/api/breeds/image/random";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://dog.ceo/api/breeds/image/random',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
));
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response, TRUE);
if(!empty($response['message'])){
echo "<img src='{$response['message']}'/>";
}else{
echo "<img src='not_found.png'/>";
}
我想设置图像但在第 8 行出现错误
<?php
$url = "https://dog.ceo/api/breeds/image/random";
$json = file_get_content($url);
$obj = json_decode($json, TRUE);
foreach($obj as $key) if
(
echo <img src='$key['message']'/>
else
echo <img src='not_found.png'/>
);
?>
有什么解决办法?
您不需要 foreach
循环作为 api returns 常规 json。也许你想得到这样的结果。
$url = "https://dog.ceo/api/breeds/image/random";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://dog.ceo/api/breeds/image/random',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
));
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response, TRUE);
if(!empty($response['message'])){
echo "<img src='{$response['message']}'/>";
}else{
echo "<img src='not_found.png'/>";
}