【问题标题】:Return result of recursive function递归函数的返回结果
【发布时间】:2019-07-02 21:36:10
【问题描述】:

我得到了一个递归函数,目前echo 的结果。我希望这个函数返回结果并在标记内使用foreach 循环它们。

我知道我应该对每个数组使用某种迭代来获得我想要的结果,但没有成功。目前我的代码看起来像这样(尝试迭代):

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;
}

以及传入函数的数组:

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

目前它只返回第一级子类别“沙漠”,而没有返回“太空”。

作为期望的结果,我希望函数返回具有 $depth 的所有类别和多个子类别的无限路径(与当前 echo 执行相同的工作)。

感谢您的建议

【问题讨论】:

  • 您没有对递归调用的结果做任何事情:self::recursiveChildCategory($category['child'], $depth + 1, $i++);
  • 每次使用函数时,都会为 $ca 值分配一个空数组,并且从不使用 $depth(与 $i 相同)所以试试这个 recursiveChildCategory($categories = array(), $i = 0, $ca = []),删除 @ 987654332@ 来自函数,现在执行 self::recursiveChildCategory($category['child'], $i++, $ca);
  • 是的,我明白了。我尝试了多种变体,这是其中之一:\
  • 您可以编辑您的问题并添加所需的输出吗?
  • @MickaëlLeger 只要您不使用递归调用的返回值,您将永远不会看到内部数组中的任何内容,因此除非您通过引用传递$ca,否则您的更改将不会做任何东西。

标签: php


【解决方案1】:

试试这个,告诉我它是否是你要找的:

我的测试数组

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

递归函数

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;
}

现在,如何使用它

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

这是输出

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"
  }
}

这是一个测试它的链接:http://sandbox.onlinephpfunctions.com/

编辑我做了一些修改,因为在 OP 示例数组中,第一个“深度”可能有多个结果,这里是“新”解决方案:

用于测试的数组:

$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" =>  [ ] ] ]
                        ]
                    ]
                ]
            ]
        ]
    ];

函数:我只是添加$ca[$depth][]而不是$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;
}

现在结果

$test = recursiveChildCategory($array);

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

输出是:

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

在这里测试:link

【讨论】:

  • 感谢您的回复,我已经尝试过功能,但它仍然只是打印出子类别的顶部sandbox.onlinephpfunctions.com/code/…
  • 在您的示例中,您从不调用该函数,并且您使用的数组不一样...它对我有用,只要您可以有多个具有相同“深度”的结果,您就无法创建一个结果数组为$c[$depth] 否则它将覆盖以前的结果
  • 这是另一个使用新解决方案的示例:sandbox.onlinephpfunctions.com/code/…
  • 对不起,我忘了在这里发帖。我提出了这个解决方案并按预期工作sandbox.onlinephpfunctions.com/code/… 当你指出我正确的方向时,我会将答案标记为合法。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-04
  • 2021-09-01
  • 2016-05-06
  • 1970-01-01
  • 2016-09-15
  • 2016-01-22
  • 2020-11-02
相关资源
最近更新 更多