AV1611 Posted February 12, 2010 Share Posted February 12, 2010 First, long time no see for those who remember me I have a question about foreach loops and arrays. I know how to foreach the elements of an array $array=array("a","b","C"); $i=0; $c=count($array); while($i < $c){ //do something with element $array[$i] $i++; } that's just an example but I want to be able to do it with a multi array: $array= a[0]item a[1]item a[2]item b[0]item b[1]item b[2]item so I want to foreach the $array[] then while that's going I want to foreach the $array[][] within that. foreach $array[]{ foreach $array[][]{ } } Not sure how to do that. wow, hope that makes sense Quote Link to comment Share on other sites More sharing options...
wildteen88 Posted February 12, 2010 Share Posted February 12, 2010 A basic example $array = array(); $array[] = array('a', 'b', 'c'); $array[] = array('e', 'f', 'g'); // convert multi-dimensional array above into a simple table echo '<table border=1>'; foreach($array as $sub_array) { echo '<tr>'; foreach($sub_array as $item) { echo "<td>$item</td>"; } echo '</tr>'; } echo '</table>'; Quote Link to comment Share on other sites More sharing options...
highrevhosting Posted February 12, 2010 Share Posted February 12, 2010 If I am not mistaking your array kind of looks like this? <? $array[a][1] = 'item1'; $array[a][2] = 'item2'; $array[a][3] = 'item3'; $array[b][1] = 'itemb1'; $array[b][2] = 'itemb2'; $array[b][3] = 'itemb3'; $array[c][1] = 'itemc1'; $array[c][2] = 'itemc2'; $array[c][3] = 'itemc3'; I think you want to do is <? foreach($array as $key => $val) { echo "Currently ".$key."<br>"; foreach($val as $k=>$v) { echo "$k => $v <br/>"; } echo "<br>"; } ?> This will output Currently a 1 => item1 2 => item2 3 => item3 Currently b 1 => itemb1 2 => itemb2 3 => itemb3 Currently c 1 => itemc1 2 => itemc2 3 => itemc3 Quote Link to comment Share on other sites More sharing options...
AV1611 Posted February 12, 2010 Author Share Posted February 12, 2010 One last question before I can mark my problem solved and I'll post my code when I'm done to help others... In the multi array, the sub arrays are numbered. The array themselves are not numbers $array['Name'][0] $array['Name'][1] $array['Name2'][0] $array['Name2'][1] ... and so on I know that $array['Name'] is the name of the element, but is there a way to echo the element name? Quote Link to comment Share on other sites More sharing options...
AV1611 Posted February 12, 2010 Author Share Posted February 12, 2010 N/M Found it... foreach ($array as $k => $v) { echo "$k<br />"; } Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.