简体   繁体   中英

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. 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>

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.

Or, you could be smart and do like @andrewsi says.

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:

$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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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