在PHP中重置一个foreach循环进行多次运行 [英] Reset a foreach loop in PHP for multiple runs

查看:539
本文介绍了在PHP中重置一个foreach循环进行多次运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要填写9个下拉框的表单。我使用foreach循环来列出选项,但是将代码复制到第二个下拉列表中不会产生任何选项。我想这是因为结果已经循环,所以什么也找不到。



如何重置每个循环的结果?或者有一种更有效的方法可以实现这一点,有人可能知道。



这是查询:

  $ qry2 =选择ride_id,名字从tpf_rides在哪里park_id = $ park_id ORDER BY名字ASC; 
$ res2 = $ pdo-> query($ qry2);

这就是我正在使用的循环:

 < select name =ride_id_image> 
< option value =>选择乘车< / option>

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

谢谢

解决方案 div>

有一个更有效的方法来做到这一点。

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $' <?php

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

?>

现在,无论何时打印选项,只需要输出字符串:

 < select name =ride_id_image> 
< option value =>选择乘车< / option>
<?php echo $ options?>
< / select>


I have a form with 9 dropdown boxes that need to be populated by the same query. I use a foreach loop to list the options but copying the code to the scond dropdown produces no options. 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>

这篇关于在PHP中重置一个foreach循环进行多次运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆