PHP在一个页面上多次执行数组

时间:2013-08-13 10:24:01

标签: php arrays

我想在一个页面上运行两个单独的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会允许我再次使用它但这似乎并非如此?这里最好的方法是什么?

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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>";