【问题标题】:simple relationship recursion简单关系递归
【发布时间】:2021-12-09 11:05:17
【问题描述】:

我有以下代码:

$indexes = [
    ['id' => 1, 'parentid' => 0, 'route' => 'root', 'title' => 'root'],
    ['id' => 2, 'parentid' => 1, 'route' => 'parent', 'title' => 'parent'],
    ['id' => 3, 'parentid' => 2, 'route' => 'child', 'title' => 'child']
];
$parentid = 1;
$indexes = buildSubs($indexes, $parentid);
var_dump($indexes);
function buildSubs(array $elms, int $parentId = 0)
{
    $branch = [];
    foreach ($elms as $elm) {
        if ($elm['parentid'] == $parentId) {
            $children = buildSubs($elms, $elm['id']);
            if ($children) {
                $elms['pages'] = $children;
            }
            $branch[] = $elm;
        }
    }
    return $branch;
}

我希望得到一个这种格式的数组:

$index=[
  [
    'id'=>1,
    'pages' => [
       [
         'id'=>2,
         'pages' => [
          [
            'id'=>3
          ]
     ]
];

子路由被封装到第二个数组中的pages 数组中,id 2 和 id 2 在 pages 数组中 id 1 中。

似乎没有按预期工作,并且无法弄清楚。

【问题讨论】:

  • 您能更具体地说明问题吗?当前输出是多少?
  • 当他们添加工作代码时,我只是运行它3v4l.org/PdsAi
  • 我认为你只是不小心在elms['pages'] 中添加了一个 s,我只用elm 尝试过它并且它有效,我相信 parentId 应该以 0 开头对吗?

标签: php recursion


【解决方案1】:

您的代码按预期工作,您只是使用了整个数组$elms 而不是$elm。此外,如果您想要整个树/路线,您需要从 0 处的 $parentId 开始。然后使用更改了变量名称和父 ID 的代码,您将获得结果数组:

Array
(
    [0] => Array
        (
            [id] => 1
            [parentid] => 0
            [route] => root
            [title] => root
            [pages] => Array
                (
                    [0] => Array
                        (
                            [id] => 2
                            [parentid] => 1
                            [route] => parent
                            [title] => parent
                            [pages] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 3
                                            [parentid] => 2
                                            [route] => child
                                            [title] => child
                                        )

                                )

                        )

                )

        )

)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 2012-04-19
    • 2014-12-26
    • 1970-01-01
    相关资源
    最近更新 更多