Web Analytics Made Easy -
StatCounter nested foreach loops - CodingForum

Announcement

Collapse
No announcement yet.

nested foreach loops

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • nested foreach loops

    howdy all,
    Can you have nested foreach loops? I have two arrays that I need to display in order "example below"

    Thank you for showing 123 anywhere street. (123 anywhere) array1.
    1 hour notice. (1 hour notice)array2


    Thank you for showing 234 somesuch place. (234 somesuch place)array1
    4 hour notice required. (4 hour notice require)array2

    That is my required result.
    Here is the code I am working with
    Code:
    foreach ($tempadx as $key => $value2){
    echo "<h1> Thank You For Showing <font color='#0000FF'>".$value2."</font>!!!</h1>";
    
    foreach ($showingi as $key => $value){
     echo "<fieldset><legend><strong>Showing Instructions for ".$value2."</strong></legend><strong>".$value."</strong></fieldset>";}}

    the results I get now are:

    Thank you for showing 234 somesuch place. (234 somesuch place)array1
    1 hour notice. (1 hour notice)array2
    4 hour notice required. (4 hour notice require)array2


    Thank you for showing 123 anywhere street (123 anywhere street )array1
    1 hour notice. (1 hour notice)array2
    4 hour notice required. (4 hour notice require)array2


    tia

  • #2
    The problem with using the second foreach loop here is that it'll always loop through the entire array unless you set up some checks to make sure it's only going over the array elements that relate to the specific content being served by your outer loop's current iteration. You'd be better off setting this up as one multidimensional array, then you can do something like:

    PHP Code:
    $array = array('123 anywhere street' => array('1 hour notice'),
                         
    '234 somesuch place.' => array('4 hour notice required',
                                                                       
    'not on Wednesday'));

    foreach( 
    $array as $key=>$value)
    {
      echo 
    'stuff for ' $key '<br>';
      foreach( 
    $value as $value2 )
      {
         echo 
    'stuff for ' $value2 '<br>'
      
    }

    Comment

    Working...
    X