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 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料