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

问题描述 投票:0回答:2

目前我有这个循环。

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-->标记。

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

谢谢

php wordpress
2个回答
2
投票

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

$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>';
}

0
投票

一个简单的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
 }
}
© www.soinside.com 2019 - 2024. All rights reserved.