douyin7416 2019-06-28 08:22
浏览 46
已采纳

返回递归函数的结果

I got a recursive function which currently echo the results. I want this function to return results and loop them with foreach inside markup.

I understand that i should use some kind of iteration for each array to get my desired result but have failed with that. Currently my code look like this(with attempts to iterate):

public static function recursiveChildCategory($categories = array(), $depth = 0, $i = 0) {
    $ca = [];

    // Loop through categories
    foreach($categories as $key => $category){
        echo str_repeat("  ", $depth);
        echo "<a href='".implode('/', $category['breadcrumb'])."'>{$category['title']}</a>";
        echo '<br>';

       $ca[$i] = [
           'id' => $category['id'],
           'title' => $category['title'],
       ];

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

And incoming array to the function:

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 ( ) 
                    ) 
                ) 
            ) 
        ) 
    ) 
)

Currently it just returns first level of child categories "Deserts", but nothing about "Space".

As desired result i want function to return all categories with $depth and infinite path to multiple child categoires (to do the same work as currently echo doing).

Thanks in advice

  • 写回答

1条回答 默认 最新

  • douhui8025 2019-06-28 08:59
    关注

    Try this and tell me if it's what you are looking for :

    The array for my test :

    $array = [
        0 => [
            "id" => 7,
            "title" => "Deserts",
            "slug" => "deserts",
            "child" => [
                0 => [
                    "id" => 8,
                    "title" => "Space",
                    "slug" => "space",
                    "child" => [
                        0 => [
                            "id" => 9,
                            "title" => "Test",
                            "slug" => "test"
                        ]
                    ]
                ]
            ]
        ]    
    ];
    

    The recursive function :

    function recursiveChildCategory($categories, $depth = 0, $ca = []) {
        // Loop through categories
        foreach($categories as $key => $category){
           $ca[$depth] = [
               'id' => $category['id'],
               'title' => $category['title'],
           ];
    
           if(isset($category['child'])) {
               // Loop
               $ca = recursiveChildCategory($category['child'], $depth + 1, $ca);
           } else {
                break;
           }
       }
       return $ca;
    }
    

    Now, how to use it :

    $test = recursiveChildCategory($array);
    var_dump($test);
    

    And this is the output :

    array(3) {
      [0]=>
      array(2) {
        ["id"]=>
        int(7)
        ["title"]=>
        string(7) "Deserts"
      }
      [1]=>
      array(2) {
        ["id"]=>
        int(8)
        ["title"]=>
        string(5) "Space"
      }
      [2]=>
      array(2) {
        ["id"]=>
        int(9)
        ["title"]=>
        string(4) "Test"
      }
    }
    

    Here is a link to test it : http://sandbox.onlinephpfunctions.com/

    EDIT : I made some modification because in OP example array can have multiple result in first "depth", here is the "new" solution :

    The array for test :

    $array = [ 
        "0" => 
            [ "id" => 3, "title" => "Subcat", "slug" => "subcat", "child" => 
                [ "0" => 
                    [ "id" => 5, "title" => "Subsubcat2", "slug" => "subcat2", "child" => 
                        [ "0" =>
                            [ "id" => "", "title" => "", "slug" =>"", "breadcrumb" => [ "0" => "homeworld", "1" => "cat", "2" => "subcat", "3" => "subcat2" ], "child" => [ ] ] 
                        ]
                    ] 
                ]
            ],
    
        "1" => 
            [ "id" => 4, "title" => "Kalahari", "slug" => "kalahari", "child" => 
                [ "0" => [ "id" => 7, "title" => "deserts", "slug" => "deserts", "child" =>
                    [ "0" => 
                        [ "id" => 8, "title" => "Ural", "slug" => "ural", "child" => 
                            [ "0" => [ "id" =>"", "title" =>"", "slug" =>"", "child" =>  [ ] ] ]
                            ]
                        ]
                    ]
                ]
            ]
        ];
    

    The function : I just add $ca[$depth][] instead of $ca[$depth]

    function recursiveChildCategory($categories, $depth = 0, $ca = []) {
        // Loop through categories
        foreach($categories as $key => $category){
           $ca[$depth][] = [
               'id' => $category['id'],
               'title' => $category['title'],
           ];
    
           if(isset($category['child'])) {
               // Loop
               $ca = recursiveChildCategory($category['child'], $depth + 1, $ca);
           } else {
                break;
           }
       }
       return $ca;
    }
    

    And now the result :

    $test = recursiveChildCategory($array);
    
    foreach ($test as $depth => $c) {
        echo "depth : ".$depth."
    ";
        foreach ($c as $result) {
            echo "Title : ".$result['title']."
    ";
        }
         echo "=============
    ";
    }
    

    The output is :

    depth : 0
    Title : Subcat
    Title : Kalahari
    =============
    depth : 1
    Title : Subsubcat2
    Title : deserts
    =============
    depth : 2
    Title : 
    Title : Ural
    =============
    depth : 3
    Title : 
    =============
    

    Test here : link

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 用vivado写数字逻辑实验报告撰写,FPGA实验
  • ¥15 为什么shp文件会有这种小方块?
  • ¥15 ecplise在连接数据库时显示加载驱动成功但是数据库连接失败
  • ¥15 visionmaster启动失败,提示为“机器不满足授权而被禁用”
  • ¥15 IDEA中圈复杂度如何具体设置
  • ¥50 labview采集不了数据
  • ¥15 Multisim红外倒车雷达仿真中距离问题
  • ¥15 请上面代码做什么处理或什么混淆
  • ¥15 英雄联盟自定义房间置顶
  • ¥15 W5500网线插上无反应