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

返回递归函数的结果

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

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题