php - How can I loop over this multi dimensional array? -


so im trying loop on array of categories , sub-categories im having trouble foreach loop. once i've got array working im going create menu if hover on category, sub categories appear.

put way, im hopeless @ logic side of things :| array along loops i've tried:

$categories = array(         'arr' => array(            'cat'=>'sport',            'subcats'=> array(                "surfing", "basketball", "nfl", "afl"             )         ),         'arr' => array(            'cat'=>'automotive',            'subcats'=> array(                "cars", "f1", "bikes", "etc"             )         ),         'arr' => array(            'cat'=>'comedy',            'subcats'=> array(                "stand up", "pranks", "...", "test"             )         )    );     //loop1   foreach ($categories $key => $value) {         if($key == "arr"){             foreach ($key $key => $value) {                 echo $value;                 if($key == "cat"){                     echo "cat";                 }                 else{                     echo $value;                 }             }             // echo $key . "<br />";             // if($key == 'subcats'){             // echo "________".$key."<br />";             // }         }     }       //attempt number 2     foreach ($categories $key => $value) {         if($key == "arr"){             while($key){                 echo $value;                 if($key == "cat"){                     echo $value;                 }                 if($key == "subcats"){                     while($key){                         echo $value[$key];                     }                 }             }         }     } 

updated code tried after this

this works okay problem loop through last arr=>array() , not of ones before.

$i=0;     foreach ($categories $key => $value) {     if($key == "arr"){         foreach ($categories['arr'] $sub => $val) {             if($sub == "cat"){                 echo $val . " => ";             }             else if($sub == "subcats"){                 for($i=0; $i<4; $i++){                     echo $val[$i] . ", ";                 }             }         }     } } 

if can reorganize array, can stick categories keys, subcategories values:

$categories = array(         'sport' => array(                "surfing", "basketball", "nfl", "afl"         ),         'automotive' => array(                "cars", "f1", "bikes", "etc"         ),         'comedy' => array(                "stand up", "pranks", "...", "test"             )   );  // here imploded list, don't need second loop  foreach($categories $cat => $subcat) {         echo "<h1>".$cat."</h1>";         echo '<ul>';         echo '<li>'.implode('</li>'.php_eol.'<li>',$subcat).'</li>';         echo '</ul>';     } 

Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -