简体   繁体   English

重置PHP中的foreach循环以多次运行

[英]Reset a foreach loop in PHP for multiple runs

I have a form with 9 dropdown boxes that need to be populated by the same query. 我有一个带有9个下拉框的表单,需要由同一查询填充。 I use a foreach loop to list the options but copying the code to the scond dropdown produces no options. 我使用foreach循环列出选项,但是将代码复制到scond下拉列表中不会产生任何选项。 I guess it's because the result has already cycled so finds nothing. 我猜是因为结果已经循环,所以什么也没找到。

How can I reset the result ready for each loop? 如何为每个循环重新设置结果? Or maybe there is a more efficient way to achieve this that someone might know. 或者,也许有一种更有效的方式来实现这一点,这也许有人会知道。

This is the query: 这是查询:

$qry2 = "SELECT ride_id, name FROM tpf_rides WHERE park_id = $park_id ORDER BY name ASC";
        $res2 = $pdo->query($qry2);

and this is the loop I am using: 这是我正在使用的循环:

<select name="ride_id_image">
    <option value="">Select Ride</option>

<?php   foreach ($res2 as $row2) {
    printf('<option value="%s">%s</option>' . PHP_EOL, $row2['ride_id'], $row2['name'] );
 } ?>
    </select>

Thanks 谢谢

There's a much more effective way to do this. 有一种更有效的方法可以做到这一点。 Instead of running through the result set multiple times, write it to a string once, and then you can re-use that as often as you need to: 不必多次遍历结果集,而是将其写入一次字符串,然后可以根据需要多次重复使用它:

<?php   

$options = "";

foreach ($res2 as $row2) {
    $options .= sprintf('<option value="%s">%s</option>' . PHP_EOL, $row2['ride_id'], $row2['name'] );
 } 

 ?>

Now, whenever you want to print the options, you can just echo out your string: 现在,每当您要打印选项时,都可以回显您的字符串:

<select name="ride_id_image">
    <option value="">Select Ride</option>
    <?php echo $options ?>    
    </select>

On first run, copy the data from the result set into an array. 第一次运行时,将结果集中的数据复制到数组中。 On each subsequent run, perform the foreach over the array instead of the result set. 在每个后续运行中,对数组而不是结果集执行foreach

Or, you could be smart and do like @andrewsi says. 或者,您可能很聪明,像@andrewsi所说的那样做。

Andrewsi's answer is the most efficient. 安德鲁西的答案是最有效的。 But to answer what you are trying to accomplish, you can just get the array from the PDO: 但是要回答您要完成的任务,您可以从PDO获取阵列:

$qry2 = "SELECT ride_id, name FROM tpf_rides WHERE park_id = $park_id ORDER BY name ASC";
$result = $pdo->query($qry2);
$res2 = $result->fetch(PDO::FETCH_ASSOC);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM