使用递归函数按键获取数组数据

时间:2019-06-25 07:56:03

标签: php

函数使数组循环通过,以获取所选类别的所有子类别。数组看起来像:

Array ( 
    [0] => Array ( 
        [id] => 7 
        [title] => Deserts 
        [slug] => deserts 
        [child] => Array ( 
            [0] => Array ( 
                [id] => 8 
                [title] => Space 
                [slug] => space 
                [child] => Array ( 
                    [0] => Array ( 
                        [id] => 
                        [title] => 
                        [slug] => 
                        [child] => Array ( ) 
                    ) 
                ) 
            ) 
        ) 
    ) 
)

我想出了一个代码来显示foreach()循环中的所有值,但是当我需要一个确切的键(例如$category['id']

)中的数据时,我无法使一切正常
public static function recursiveChildCategory($categories = [], $depth = 0) {

        // Loop through categories
        foreach($categories as $category){

        // If $category is an array.
        if(is_array($category)){

            // Drop empty arrays
            $filteredCategory = array_filter($category);

            // Loop
            self::recursiveChildCategory($filteredCategory, $depth + 1);
        } else {
            //It is not an array, so print it out
       echo str_repeat("&nbsp;&nbsp;", $depth), $category, '<br>';

        }
    }
}

当前变量$category仅输出所有值。我想分别获取所有信息,例如$category['id']$category['title']等。

感谢您的咨询

1 个答案:

答案 0 :(得分:1)

仅测试字段名称值,请参见

    public static function recursiveChildCategory($categories = [], $depth = 0) {
            // Loop through categories
            foreach($categories as $category){

            // If $category is an array.
            if(is_array($category)){

                // Drop empty arrays
                $filteredCategory = array_filter($category);

                // Loop
                self::recursiveChildCategory($filteredCategory, $depth + 1);
            } else {
                //It is not an array, so print it out
                if($fieldOrIndex === 'id') {
                   echo str_repeat("&nbsp;&nbsp;", $depth), $category, '<br>';
                }
            }
        }
    }

要获得类别中每个字段的单独树印,我认为您必须为每个字段调用该函数。用函数arg替换“ id”字符串,并用“ id”,“ title”等调用它。

编辑:具有所有类别数据,例如创建链接:

public static function recursiveChildCategory($categories = [], $depth = 0) {
    // Loop through categories
    foreach($categories as $category){
        echo str_repeat("&nbsp;&nbsp;", $depth);
        echo "<a href='foo_bar_{$category['id']}'>{$category['title']}</a>";
        echo '<br>';

        if(isset($category['child'])){
            // Loop
            self::recursiveChildCategory($category['child'], $depth + 1);
        } 
    }
}