使用PHP foreach在内容之间插入自定义HTML实体


insert custom html entities between content using php foreach

我使用简单的dom解析器http://simplehtmldom.sourceforge.net/manual.htm

表示我有这样的表

<table class="tb">...</table>
<table class="tb">...</table>
<table class="tb">...</table>
<table class="tb">...</table>
<table class="tb">...</table>

I do

$ads = "<div>ads banner here</div>";
foreach($html->find('div[class="tb"]') as $element){
       echo $element->src . '<br>';
       $element->outertext .= $ads;
}

然后广告横幅将循环遍历所有表格,我将得到5个广告块。如何限制数量?就像我想只有一个广告块出现在第一个和第二个表。

foreach($html->find('div[class="tb"]') as $i => $element){

假设数组使用索引键$i是你的迭代索引,从0开始,所以当你有足够的

时,要限制数量,打破循环
foreach($html->find('div[class="tb"]') as $i => $element){
    if ($i > 0) break; // show only the first
    // if ($i > 4) break; // show the first 5
    echo $element->src . '<br>';
    $element->outertext .= $ads;
}

如果使用关联数组,则改为计数。

$i = 0;
foreach($html->find('div[class="tb"]') as $element){
    $i++;
    if ($i > 1) break; // show only the first
    // if ($i > 5) break; // show the first five
    echo $element->src . '<br>';
    $element->outertext .= $ads;
}