I have a loop with different json. Inside the json, there are images some of which have a description and some do not. I want when the description is "Main image" then to bring specific url. But when the description is different from "Main image", then bring another image which I have set.
Τhe problem is that it shows me both images, because in some json there is a blank description but also this description is "Main image"
My code is:
$no_image = get_stylesheet_directory_uri().'/img/no_image.png';
$images = $json->images;
foreach ($images as $img){
if($img->description == 'Main image'){
$main_image = $img->url;
?>
<div class="card__image" style="background-image: url(<?php echo $main_image;?>)"></div>
<?php
}else if($img->description==""){
<div class="card__image" style="background-image: url(<?php echo $no_image;?>)"</div>
}
}
My Answer:
present, the image is displayed with the description as well. Here is an example of how you can achieve this in PHP:
php
// Sample JSON data
$json = '{
"images": [
{
"url": "image1.jpg",
"description": "Description for image 1"
},
{
"url": "image2.jpg"
},
{
"url": "image3.jpg",
"description": "Description for image 3"
}
]
}';
// Decode the JSON data
$data = json_decode($json, true);
// Loop through the images
foreach ($data['images'] as $image) {
$imageUrl = $image['url'];
$imageDescription = isset($image['description']) ? $image['description'] : '';
// Display the image with description if available
if (!empty($imageDescription)) {
echo '';
} else {
echo '';
}
}
?>
In this code snippet, we first decode the JSON data using `json_decode()` and then loop through the images array. We check if the image has a description using `isset()` and then display the image with the description if available. Otherwise, we just display the image without the description.
Rate this post
5 of 5 based on 2747 votesComments