如何循环遍历这个多维数组



所以我试图在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(),而不是之前的任何一个。

$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] . ", ";
                }
            }
        }
    }
}

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

$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>';
    }

相关内容

  • 没有找到相关文章

最新更新