如何在PHP中迭代多维数组?

时间:2011-10-18 08:29:05

标签: php arrays multidimensional-array

我将数据结构放入我的数组$ categories

stdClass Object
(
    [37] => Array
        (
            [term_id] => 37
            [name] => Files 
            [parent] => 0
            [38] => Array
                (
                    [term_id] => 38
                    [name] => Downloads 
                    [parent] => 37
                )

        )

    [29] => Array
        (
            [term_id] => 29
            [name] => Articles 
            [parent] => 0
            [36] => Array
                (
                    [term_id] => 36
                    [name] => General
                    [parent] => 29
                )

            [35] => Array
                (
                    [term_id] => 35
                    [name] => WordPress 
                    [parent] => 29
                )

            [34] => Array
                (
                    [term_id] => 34
                    [name] => Php, Sql 
                    [parent] => 29
                )

        )

    [1] => Array
        (
            [term_id] => 1
            [name] => Uncategorized
            [parent] => 0
        )

)

现在我喜欢用以缩进方式打印以下形式的数据。

Files
    Downloads
Articles
    General
    WordPress
    Php, Sql
Uncategorized

要获得上述结果,我使用该代码

$categories = get_array_content(); // Return the above data

print_category_tree($categories);

function print_category_tree(&$c)
{
    foreach($c as $cat)
    {
        ?>
        <label>
            <input type="checkbox" value="<?php echo $cat['term_id']; ?>" /> <?php echo $cat['name']; ?>
        </label>
        <br />
        <?php

        foreach($cat as $categ)
        {
            if(is_array($categ))
            {
                print_category_tree($categ);
            }
        }
    }
}

我知道这有什么不对,但我不知道是什么。有人可以帮我多维数组迭代吗?

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:0)

你用两个参数调用函数:

print_category_tree($categ, $forum_id);

但是你的函数只需要一个参数:

function print_category_tree(&$c)

你正在使用&amp;在功能中。您可能想要在没有它的情况下进行测试。

function print_category_tree($c)