簡體   English   中英

如何在PHP中迭代多維數組?

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

我將數據結構放入我的數組$ 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);
            }
        }
    }
}

我知道有些事情是錯的,但我不知道是什么。 有人可以幫我多維數組迭代嗎?

你用兩個參數調用函數:

print_category_tree($categ, $forum_id);

但是你的函數只需要一個參數:

function print_category_tree(&$c)

而你正在使用函數中的&。 你可能想要在沒有它的情況下測試它

function print_category_tree($c)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM