My Question:
How would I echo a slide only if the json object contains an image?
My Issue:
I’m not sure how I should treat a for loop of a json object to echo a slide only if it contains an image.
Objective:
I want to be able to echo a div only if there is an image in the json object, and then echo a link around the image so I can link to the story.
Additional:
How could I not echo a slide div inside “#slides” when there is no image?
Is there something in PHP that would let me echo the slide if it contains an image without breaking the foreach loop?
Or am I going to have to break the foreach loop,store the information for only the slides holding an image and re-loop through them? If so what would be the best way to do so?
I’m lost because if I make an if statement for $key==”img” its only going to echo the image portion, not sure how I should handle it.
Code:
NEWS.JSON
{
"1": {
"id": "1",
"img":"./images/newspost/07-05-12.jpg",
"link":"http://www.cnn.com/2012/07/05/world/europe/france-air-crash-report/index.html",
"title": "Example",
"date":"02/08/12",
"content": "Example"
},
"2": {
"id": "2",
"img":"",
"link":"http://online.wsj.com/article/SB10001424052702304141204577508500189367804.html?mod=googlenews_wsj",
"title": "Example",
"date":"09/03/10",
"content": "Example"
}
}
HOME.PHP
/* Error Report on */
error_reporting(E_ALL);
/* Open Json file */
$json = file_get_contents("./content/news.json");
/* Setup iterator to go through file */
$jsonIterator = new RecursiveIteratorIterator(new RecursiveArrayIterator(json_decode($json, TRUE)),RecursiveIteratorIterator::SELF_FIRST);
/* Create SLIDES for SLIDESHOW */
echo "<div id='slides'>";
At this point I DON’T want to echo anything if no image exists.
foreach($jsonIterator as $key => $val)
{
if(is_array($val))
{
echo "<div>";
}
if($key=="link")
{
echo "<a href='$val'>";
}
if($key=="img"&&$val!="")
{
echo "<img alt='' src='$val'></img>";
}
if(!is_array($val)&&$key=="content")
{
echo "</a>";
echo "</div>";
}
}
End loop/what needs to show only if image exists.
echo "</div>";
/* End SLIDES creation */
I show you the way how I would do it:
I think it’s much more simpler than your way.