Home > Software engineering >  simple relationship recursion
simple relationship recursion

Time:10-23

I have the following code:

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

I'd like to end up with an array in this format:

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

where the child route is encapsulated into a pages array within the 2nd array with id 2, and id 2 being inside the pages array inside id 1.

Doesn't seem to be working as expected, and am having trouble figuring it out.

CodePudding user response:

Your code works as intended, you just used the whole array$elms instead of $elm. Also, if you wanted the whole tree / route you need to start with the $parentId at 0. Then using your code with the changed variable name and parent id, you get the resulting array:

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
                                        )

                                )

                        )

                )

        )

)
  • Related