Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Hoe do I Loop through multi-diminsional array??

Status
Not open for further replies.

Lynux

MIS
Aug 3, 2001
33
US
I am needing to loop throgh a mulit-dininsional array
(example: $norm_table_info[0][1])
Ho wo I loop through both key value pairs?

((example here is what I would typically do for a one diminsional array))
----------->
reset($norm_table_info);
while (list($k, $v) = each($norm_table_info)){
echo $k .&quot; - &quot; .$v .&quot;<br>&quot;;
}
============================================

Thanks in advance!!! :) =================================
Imagination is more important than knowledge.
(A.E.)
 
If you know how deep your multidimensional array is, you could just nest your while statements, or better yet, nest your foreach statements. Here is an example with a two-dimensional array:

Code:
reset($norm_table_info);

foreach ($norm_table_info as $k => $v){
   if(is_array($k){
      foreach ($k as $nk => $nv){
         echo $nk . &quot; - &quot; . $nv . &quot;<br>&quot;;
      }
   }
   else{
      echo  $k .&quot; - &quot; .$v .&quot;<br>&quot;;
   }
}

However, PHP has provided a really cool function that packages this behavior, and allows you to perform a certain function on every node of an array. It's called array_walk(). ( see ) With a little creativity, we can make this function call itself recursively until it has visited every node on a many-dimensional array. Here is an example:
Code:
// Part A: first we define the function that will be applied to every element
// this function recursively calls itself, until it visits every node on the tree

function test_print ($item, $key) {
    if(is_array($item)){
    array_walk($item, 'test_print');
    }
    else
    {
      if($key)
      {
        echo &quot;$key - $item, &quot;;
      }
    }

    if(is_array($item)){
      echo '<br>';
    }
} // end function 'test_print'

// Part B: now we run that function through the array:
// this will visit each node of the tree, and output the row

array_walk($my_array, 'test_print');

Also, I have placed a code snippet at SourceForge, showing how to turn SQL queries into multidimensional arrays, and then process them in this way: -------------------------------------------

&quot;Calculus is just the meaningless manipulation of higher symbols&quot;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-unknown F student
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top