我怎样才能遍历这个多维数组呢?

时间:2015-08-03 05:34:52

标签: php arrays multidimensional-array

所以我试图循环遍历categoriessub-categories的数组,但我遇到了foreach loop的问题。一旦我使阵列正常工作,我将创建一个菜单,如果您将鼠标悬停在某个类别上,则会显示子类别。

这样说,我对事物的逻辑方面毫无希望:| 这是我的阵列以及我尝试过的循环:

$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 as $key => $value) {
        if($key == "arr"){
            foreach ($key as $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 as $key => $value) {
        if($key == "arr"){
            while($key){
                echo $value;
                if($key == "cat"){
                    echo $value;
                }
                if($key == "subcats"){
                    while($key){
                        echo $value[$key];
                    }
                }
            }
        }
    }

我在此

之后尝试更新的代码

这没关系,但唯一的问题是它只会循环通过最后一个arr=>array()而不是之前的任何一个。{/ p>

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

1 个答案:

答案 0 :(得分:2)

如果您可以重组数组,可以将类别作为键,子类别作为值:

$categories = array(
        'sport' => array(
               "surfing", "basketball", "nfl", "afl"
        ),
        'Automotive' => array(
               "cars", "f1", "bikes", "etc"
        ),
        'comedy' => array(
               "stand up", "pranks", "...", "test"
            )
  );
 // Here is an imploded list, you don't need a second loop then
 foreach($categories as $cat => $subcat) {
        echo "<h1>".$cat."</h1>";
        echo '<ul>';
        echo '<li>'.implode('</li>'.PHP_EOL.'<li>',$subcat).'</li>';
        echo '</ul>';
    }