0

我想在一页上运行两个单独的 foreach 循环,但只写一次我的 SQL。例如看下面的代码,只有第一个 id 的 ul 运行,第二个 ul 为空。

    <?php
        $mylist = 'SELECT * FROM myTable';
        $showlist = $pdo->prepare($mylist);
        $showlist->execute();
    ?>  
    <ul id="first">
        <?php foreach ($showlist as $rowid):;?>
            <li><?php echo $rowid['id'] ?></li>
        <?php endforeach; ?>  
    </ul>
    <ul id="second">
        <?php foreach ($showlist as $rowname):;?>
            <li><?php echo $rowname['name'] ?></li>
        <?php endforeach; ?>  
    </ul>

我认为重命名 as 可以让我再次使用它,但似乎不是这样?这里最好的方法是什么?

4

2 回答 2

2

尝试:

<?php
$mylist = 'SELECT * FROM myTable';
$showlist = $pdo->prepare($mylist);
$showlist->execute();
$result = $showlist->fetchAll();

foreach ($result as $rowid) {
    // do stuff
}

foreach ($result as $rowname) {
    // do stuff
}
于 2013-08-13T10:29:01.160 回答
1

您需要先将元素堆叠在一个额外的数组中:

$mylist = 'SELECT * FROM myTable';
$showlist = $pdo->prepare($mylist);
$showlist->execute();

$rows = array();

foreach($showlist as $row) {
    array_push($rows, $row);
}

echo "<ul>";
foreach($rows as $row) {
    echo "<li>".$row['id']."</li>";
}
echo "</ul><ul>";
foreach($rows as $row) {
    echo "<li>".$row['name']."</li>";
}
echo "</ul>";
于 2013-08-13T10:31:29.427 回答