[nycphp-talk] walking through a multi-dimensional array
Hans Zaunere
hans at nyphp.org
Fri Jul 25 19:25:56 EDT 2003
Michael Southwell wrote:
> The following code successfully walks through a 3-element array:
>
> for ($i=1;$i<=$articlecount;++$i){
> echo "<input type=\"radio\" name=\"which\"
> value=\"".$articles[$i][0]."\" />".$articles[$i][1].":
> ".$articles[$i][2]."<br />";
> }
As a [possibly] help tip, numerically indexed arrays always start at 0, so $i should be initialized to 0 above
> I was also trying to do it with while-list-each but this doesn't work:
> while (list($key,$value)=each($articles)){
> while (list($key2,$url,$date,$title)=each($value)){
> echo "<input type=\"radio\" name=\"which\" value=\"".$url."\"
> />".$date.": ".$title."<br />";
> }
> }
The problem is each() only can return two variables; $key2 (the key) and, potentially, $value2 (an array, containing $url, $date, etc). The nested while() loops and the for() loop above do differant things.
> At this point I think the for-loop is best but for the sake of general
> knowledge, how do I do it the other way? TIA.
I would highly recommend not using the series of while loops, even if done properly; foreach() could easily do what the while() loops do, albeit still differant from what the for() loop does.
foreach( $articles as $key => $value ) {
foreach( $value as $key2 => $value2 ) {
echo "<br>$key2 => $value2";
}
}
H
More information about the talk
mailing list