Jump to content

Loop through array twice


r00tk1LL

Recommended Posts

I'm grabbing data from a SQL query and using

while ($a_row = mysql_fetch_array($result))

to loop through the results (which is working on the first loop). The problem is that the 1st set of results I want belong in 1 DIV on the page. Then I need to loop through the same array again, grabbing different data and placing it in another DIV on the page. Here's what I have:

 

	
$i = 0;
while ($a_row = mysql_fetch_array($result))
{
$i++;
//in the first DIV			
print "First set of DATA";
}

while ($a_row = mysql_fetch_array($result))
{
//in the second DIV	
print "Second set of DATA";
}

 

What am I doing wrong?

Link to comment
https://forums.phpfreaks.com/topic/67281-loop-through-array-twice/
Share on other sites

Your not actually looping through an array but a result resource. Once you reach the end, you will need to rewind it back to the beginning in order to go through it a second time.

 

<?php

while ($a_row = mysql_fetch_array($result))
{
$i++;
//in the first DIV			
print "First set of DATA";
}

mysql_data_seek($result,0); // rewind back to the first row.

while ($a_row = mysql_fetch_array($result))
{
//in the second DIV	
print "Second set of DATA";
}

?>

Or you could just loop through the data once, building the content you need for div1 and div2 at the same time.

 

<?php

while ($a_row = mysql_fetch_array($result))
{
$div1 .= "First set of DATA";

$div2 .= "Second set of DATA";
}

echo $div1;
echo $div2;

?>

To test for success use...

 

<?php

while ($a_row = mysql_fetch_array($result)) {
  print "First set of DATA";
}

if (mysql_data_seek($result,0)) { // rewind back to the first row.

  while ($a_row = mysql_fetch_array($result)) {
    print "Second set of DATA";
  }

} else {
  echo "data_seek failed";
}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.