简体   繁体   English

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

[英]How to iterate in multidimentional array in PHP?

I have that data structure into my array $categories 我将数据结构放入我的数组$ 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
        )

)

Now what I like to do is print that data in the following form with indents. 现在我喜欢做的是使用缩进以下面的形式打印数据。

Files
    Downloads
Articles
    General
    WordPress
    Php, Sql
Uncategorized

To achive the above result I use that code 为了实现上述结果,我使用了该代码

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

I know that something is wrong with that but I can't guess what. 我知道有些事情是错的,但我不知道是什么。 Can somebody please help me with multi dimentional array iteration ? 有人可以帮我多维数组迭代吗?

You call the function with two params: 你用两个参数调用函数:

print_category_tree($categ, $forum_id);

But your function takes only one param: 但是你的函数只需要一个参数:

function print_category_tree(&$c)

And you are using the & in the function. 而你正在使用函数中的&。 You might want to test it without. 你可能想要在没有它的情况下测试它

function print_category_tree($c)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM