Page 1 of 1

Nested Do Loop help needed

Posted: Wed Sep 24, 2008 10:18 am
by hotblooded
I'm trying to use nested do loops in my php code and I'm not getting the results I want.

What I want:

Dept 1
Fac1
fac2
fac3

dept2
fac4
fac5
...

But what is actually happening is:

dept1
fac1
fac2
fac3

dept2
dept3
...

Here's the code:

Code: Select all

<?php do { ?>
<h2><?php echo $row_department['Fac_Dept']; ?></h2>
<table width="100%" border="1" cellspacing="0" cellpadding="3">
 <?php do { ?>
 <?php if ($row_department['Fac_Dept'] == $row_fac['Fac_Dept']){?>
 
<table width="100%" border="1" cellspacing="0" cellpadding="3">
 <tr>
    <td width="300"><?php echo $row_fac['Fac_Title']; ?> <?php echo $row_fac['Fac_Fname']; ?> <?php echo $row_fac['Fac_Init']; ?> <?php echo $row_fac['Fac_Lname']; ?></td>
    <td><?php echo $row_fac['Fac_Office']; ?></td>
    <td><?php echo $row_fac['Fac_Phone']; ?></td>
    <td width="500"><?php echo $row_fac['Fac_Pos']; ?></td>
  </tr>
  </table><?php } ?>
<?php } while ($row_fac = mysql_fetch_assoc($fac)); ?>
<?php } while ($row_department = mysql_fetch_assoc($department)); ?>
For the life of me I can't figure out what's wrong with it

Any help is greatly appreciated...

Re: Nested Do Loop help needed

Posted: Wed Sep 24, 2008 10:31 am
by gethinw
you need to "reset($arr);" the array of the inner loop, or just use foreach which I find much better for looping through arrays

Re: Nested Do Loop help needed

Posted: Wed Sep 24, 2008 11:26 am
by hotblooded
Using the reset() function <?php reset($row_fac); ?> , I am getting the error:

Warning: reset() [function.reset]: Passed variable is not an array or object in C:\wamp\www\newland\facstaff_mod.php on line 54

Where should I place the reset() function within the nested loops?

Also, is it possible to nest foreach statements or did i just misunderstand how it works?

Thanks

Re: Nested Do Loop help needed

Posted: Wed Sep 24, 2008 1:49 pm
by gethinw
I think you need to reset mysql_fetch_assoc($fac) but I'm not 100% certain (I usually use the foreach method).

And yes, foreach can be nested.