foreach数组数组

时间:2014-10-06 12:57:28

标签: php arrays

我正在尝试添加Array of Array中的元素

$categoryTreeStructure[$grantCategoryName][$parentCategoryName][$subCategoryText]['text'] =$subCategoryText;
// GET CHILD CATEGORY URL
$categoryTreeStructure[$grantCategoryName][$parentCategoryName][$subCategoryText]['url'] = $childPageLink;

我尝试将每个类别循环为

foreach($categoryTreeStructure as $categoryName => $subCategories ){
echo $categoryName."<br>";
}

我在$categoryName中空白了。 我需要遍历每个类别,我该怎么做?

2 个答案:

答案 0 :(得分:0)

foreach($categoryTreeStructure as $categoryName => $subCategories ){
 foreach($subCategories as $key => $val){
    foreach($val as $subkey => $subval){
        echo $subval['text'] . "<br>";
        echo $subval['url'];
    }
 }
}

我能看到它工作的唯一方法是使用嵌套循环

答案 1 :(得分:0)

您的问题是阵列的第二个维度不是目标。你的数组看起来像这样:

Array
(
    [] => Array
        (
            [] => Array
                (
                    [foo] => Array
                        (
                            [text] => foo
                            [url] => Bar
                        )

                )

        )

)

如果你想接受你的数据,你会很高兴这样的预告:

foreach($categoryTreeStructure[$parentCategoryName] as $categoryName ){
        print_r($categoryName);
}

这将输出:

Array
(
    [foo] => Array
        (
            [text] => foo
            [url] => Bar
        )

)

但是在你的例子中你想要直接文本:

foreach($categoryTreeStructure[$grantCategoryName][$parentCategoryName][$subCategoryText] as $categoryName ){
        echo $categoryName;

}

这将输出:

foo
Bar

这是你的例子的答案,因为你的例子只能在最后一个数组中循环,但如果你有多个subCategoryText,你需要有像@Rossco那样的嵌套循环:

foreach($categoryTreeStructure as $categoryName => $subCategories ){
 foreach($subCategories as $key => $val){
    foreach($val as $subkey => $subval){
        echo $subval['text'] . "<br>";
        echo $subval['url'];
    }
 }
}