如何把样式两个foreach语句输出PHP


How to put to style two foreach statements output PHP

如何将第一个foreach语句的输出放在表的一列中,而将另一个foreach语句的输出放在另一列中?我尝试了一些东西,但由于某种原因,它把它们都放在了一个栏里。下面是我的代码:

<table border="0" align="center">
<?php
foreach($anchors as $a) {
    $text = $a->nodeValue;
    $href = $a->getAttribute('href');
    $i++;
    if ($i > 16) {
        if (strpos($text, "by owner") === false) {
            if (strpos($text, "map") === false) {
                echo "<tr><td><a href =' ".$href." '>".$text."</a><br/></td></tr>";
            }
        }
    }
    foreach($span as $s) {
        echo "<tr><td>".$s->nodeValue."</td></tr>";
    }
}
?>
</table>

<tr></tr>标记一行。<td></td>标记一列。要制作2列,每次迭代只使用一组<tr>标签,在它们之间使用两组<td></td>标签。

也就是说,$span到底是什么?它是否包含与$anchors相同数量的元素,并且您希望每行显示一个项目?如果是这样,你就需要稍微调整一下你的代码。有几种方法可以做到这一点——下面是一种简单的方法:

<table border="0" align="center">
<?php
$i = 0;
foreach($anchors as $a) {
    echo "<tr>";
    $text = $a->nodeValue;
    $href = $a->getAttribute('href');
    if ($i >= 16) {
        if (strpos($text, "by owner") === false) {
            if (strpos($text, "map") === false) {
                echo "<td><a href =' ".$href." '>".$text."</a><br/></td>";
            }
        }
    } else {
       echo "<td></td>";    #output a blank cell in the first column
    }
    echo "<td>" . $span[$i]->nodeValue . "</td>";
    echo "</tr>";
    ++$i
}
?>
</table>
编辑:它看起来像你的$span是一个DOMNodeList对象,而不是一个数组。我没有这方面的经验,但看起来你可以使用DOMNodelist::item函数来获取列表中的当前项目(参见http://php.net/manual/en/domnodelist.item.php): )
echo "<td>" . $span->item($i)->nodeValue . "</td>";

所以试着在我的答案中改变各自的行

没有数据的概念是很难的,但是像这样的东西可能:

   // start a table
   echo '<table>';
   // for as long as there are elements in both span and anchors
   for ($i=0; $i < $anchors->length && $i < $span->length; $i++) { 
       // start a new table row
       echo '<tr>';
       // get the current span and anchor
       $a = $anchors->item($i);
       $s = $span->item($i);
       // print them
       $text = $a->nodeValue;
       $href = $a->getAttribute('href');
       // col 1, number
       echo '<td>'.$i.'</td>';
       // col 2, anchor
       echo '<td><a href ="' .$href. '">'.$text.'</a></td>';
       // col 3, span
       echo '<td>'.$s->nodeValue.'</td>';
       // close the table row
       echo '</tr>';
    }
    // close the table
    echo '</table>';

(未测试的代码)没有实际数据很难更具体。

使用php内置的'current'和'next'。

一些提示/备注/旁注可能会对你有所帮助:
-请注意,我使用单引号,因为他们是更好的性能(双引号将被php解释)。
尽量使用尽可能少的循环(for, while, foreach)。他们是一个强大的工具,但可以快速消耗内存和性能!
-如果你正在使用多维(数组内部数组),只有嵌套循环,而这里的情况并非如此(我认为)
-尝试限制嵌套块的数量(if inside if inside if inside loop)。我试着不超过2级(当然这不是绝对的规则,只是一个很好的标准)。如果不可能,创建一个函数。
- 注释你的代码!我很难理解你的代码(我每天都写PHP为生),我可以想象你会在几周内理解。注释可能看起来像是浪费时间,但它将大大简化调试,并且在稍后更新您(或其他人)的代码时是一种祝福!

编辑:


我刚刚注意到你没有使用DOMNodeList而不是数组,所以我更新了我的代码。应该工作得很好,而且代码更干净。就像我说的,不看数据很难…