Nested Do Loop help needed

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
hotblooded
Forum Newbie
Posts: 19
Joined: Wed Sep 24, 2008 10:14 am

Nested Do Loop help needed

Post 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...
gethinw
Forum Newbie
Posts: 16
Joined: Tue Sep 23, 2008 4:02 am

Re: Nested Do Loop help needed

Post 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
hotblooded
Forum Newbie
Posts: 19
Joined: Wed Sep 24, 2008 10:14 am

Re: Nested Do Loop help needed

Post 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
gethinw
Forum Newbie
Posts: 16
Joined: Tue Sep 23, 2008 4:02 am

Re: Nested Do Loop help needed

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