仅将文本放在循环的第一个结果之后



目前我有这个循环。

foreach ($html2->find('.entry-content img') as $image) {
    $path = $image->src;    
    $start = '<img src="'.$path.'" style="height: auto; width: 100%;margin-bottom: 3px;">';
    print htmlspecialchars($start); print '<br>';
}

这是使用simple_html_dom.php从网站抓取一些图像,这部分工作得很好。但是,我需要这样做,以便它仅在foreach循环中的第一个结果之后返回WordPress <!--more-->标签。

我怎样才能实现这一目标?

谢谢

您可以尝试检查它是否是循环期间的第一个,如下所示:

$first = TRUE;
foreach ($html2->find('.entry-content img') as $image) {
$path = $image->src;    
$start = '<img src="'.$path.'" style="height: auto; width: 100%;margin-bottom: 3px;">';
if($first){
    $start .= "<!--more-->";
    $first  = FALSE;
}
print htmlspecialchars($start); print '<br>';
}
一个简单的

if就可以完成这项工作

$cond = false;
foreach($html2->find('.entry-content img') as $image) {
//Always done
if (!$cond) {
  //Will be called only during the first iterration
  $cond = true;
 }
else if ($cond){
  //This part will always be executed after the first iterration
 }
}

最新更新