仅当 json 对象包含图像时,我如何回显幻灯片


How would I echo a slide only if the json object contains an image?

我的问题:

仅当 json 对象包含图像时,如何回显幻灯片?

我的问题:

不确定我应该如何处理 json 对象的 for 循环以仅在包含图像时才回显幻灯片。

目的:

我希望只有在 json 对象中有图像时才能够回显div,然后在图像周围回显链接,以便我可以链接到故事。

附加:

当没有图像时,我怎么能不回显"#slides"内的幻灯片div?

PHP 中是否有一些东西可以让我在幻灯片包含图像而不破坏 foreach 循环的情况下回显幻灯片?

还是我将不得不打破foreach循环,仅存储包含图像的幻灯片的信息并重新循环浏览它们?如果是这样,最好的方法是什么?

我很迷路,因为如果我为 $key=="img" 做一个 if 语句,它只会回显图像部分,不确定我应该如何处理它。

法典:

新闻。杰伦

{
    "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"
    }
}

家。.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'>";

在这一点上,如果没有图像存在,我不想回显任何东西。

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>";
}
}

结束循环/仅当图像存在时才需要显示的内容。

echo "</div>";
/* End SLIDES creation */

我告诉你我怎么做:

$json = file_get_contents("./content/news.json");
$jsonArray = json_decode($json, true);
// Start slideshow...
echo "<div id='slideshow'>";
foreach ($jsonArray as $entry) {
  if ($entry['img'] == '') {
    continue; // Just don't do anything with this entry, go to next one
  }
  // News begins.
  echo "<div>";
  // For example:
  echo "<a href='" . $entry['link'] . "'>";
  // Etc.
  // News ends.
  echo "</div>";
}

我认为这比你的方式简单得多。