inorganik
inorganik

Reputation: 25525

Cannot loop through mysql results within nested foreach loops more than once

I'm finding that I can't loop through a set of mysql results more than once. Is this this something normal that I'm just not aware of?

I have 2 nested foreach loops like so:

foreach ($items as $item) {
    echo $item." ---------------<br>";
    // loop through set of results
    foreach ($mysqlresults as $result) {
        // loop through result
        echo $result." ^^^^^^^^^^<br>";
        while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
            print_r($row);
            echo "<br>";
        }
    }
}

which outputs:

item 1 ---------------
ResourceID#1 ^^^^^^^
row 1 data
row 2 data
row 3 data
row 4 data
ResourceID#2 ^^^^^^^
row 1 data
row 2 data
row 3 data
row 4 data
ResourceID#3 ^^^^^^^
row 1 data
row 2 data
row 3 data
row 4 data
item 2 ---------------
item 3 ---------------
item 4 ---------------
item 5 ---------------

Is there a good reason why it can't reloop through the results or am I doing something wrong?

Thanks.

Upvotes: 0

Views: 181

Answers (1)

Francois
Francois

Reputation: 10968

You can't because mysql_fetch_array moves a cursor through the results. You can use mysql_data_seek($result, 0) to rewind.

Upvotes: 2

Related Questions