Foreach and 2D Array in PHP

20,407

Solution 1

You would need to nest two foreach BUT, there is nothing about your data structure that easily indicates what is a sub-item. Map vs. MapA? I guess a human could figure that out, but you'll have to write a lot of boilerlate for your script to sort that.. Consider restructuring your data so that it more closely matches what you are trying to achieve.

Here's an example. You can probably come up with a better system, though:

$mainMenu = array(
    'Home' => '/mult/index.php',
    'Map' => array(
        '/mult/kar.php',
        array(
            'MapA' => '/mult/kara.php',
            'MapB' => '/mult/karb.php'
        )
     ),
     'Contact' => '/mult/sni.php',
     ...
);

Solution 2

You nest foreach statements; Something like this should do the work.

foreach($mainMenu as $key=>$val){
    foreach($val as $k=>$v){
       if($k == 2){
         echo '-' . $key;
       }else{
          echo $key;
       }
    }
}

Solution 3

Foreach can just as easily be used in multi-dimensional arrays, the same way you would use a for loop.

Regardless, your approach is a little off, here's a better (but still not great) solution:

$mainMenu['Home'][1] = '/mult/index.php';
$mainMenu['Map'][1] = '/mult/kar.php';
$mainMenu['Map']['children']['MapA'] = '/mult/kara.php';
$mainMenu['Map']['children']['MapB'] = '/mult/karb.php';
$mainMenu['Contact'][1] = '/mult/sni.php';
$mainMenu['Bla'][1] = '/mult/vid.php';

foreach($mainMenu as $k => $v){
    // echo menu item
    if(isset($v['children'])){
        foreach($v['children'] as $kk => $vv){
            // echo submenu
        }
    }
}

That said, this only does 1-level of submenus. Either way, it should help you get the idea!

Share:
20,407
ilhan
Author by

ilhan

https://www.buymeacoffee.com/ilhan

Updated on July 09, 2022

Comments

  • ilhan
    ilhan almost 2 years
    $mainMenu['Home'][1] = '/mult/index.php';
    $mainMenu['Map'][1] = '/mult/kar.php';
    $mainMenu['MapA'][2] = '/mult/kara.php';
    $mainMenu['MapB'][2] = '/mult/karb.php';
    $mainMenu['Contact'][1] = '/mult/sni.php';
    $mainMenu['Bla'][1] = '/mult/vid.php';
    


    This is a menu, 1 indicates the main part, 2 indicates the sub-menu. Like:

    Home
    Map
    -MapA
    -MapB
    Contat
    Bla

    I know how to use foreach but as far as I see it is used in 1 dimensional arrays. What I have to do in the example above?

    • Otto Allmendinger
      Otto Allmendinger about 14 years
      Your data structure isn't properly defined. What should happen when $mainMenu['MapA'][1] is set? Better use an array like this $mainMenup[] = Array( "Home", "/mult/index.php", 1)
  • Yossi Gil
    Yossi Gil about 14 years
    $mainMenu['Map'] should have [1] appended to it (or some suitable key) otherwise you just stomp the value.