Get path array from adjacency list data array

96 views Asked by At

I have an array (data from adjacency table) and it looks like:

$data = Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Anniversary
            [parent] => 0
        )

    [1] => Array
        (
            [id] => 12
            [name] => New arrives
            [parent] => 1
        )

    [2] => Array
        (
            [id] => 13
            [name] => Discount
            [parent] => 12
        )

    [3] => Array
        (
            [id] => 6
            [name] => Birthday
            [parent] => 0
        )
)

I have a function that return path array by id:

function categoryRecursion($element, $input) {

        $return = array_filter($input, function($v) use ($element) { return $v->id == $element; });
        $last   = end($return);
        $str[]  = $last;
        if($last->parent !=0) {
            $str[] = categoryRecursion($last->parent, $input);
        }
        return array_reverse($str); //implode('->',array_reverse($str));
}

When I use it:

print(categoryRecursion('13',$data));

I'm getting this output:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 1
                            [name] => Anniversary
                            [parent] => 0
                        )

                )

            [1] => stdClass Object
                (
                    [id] => 12
                    [name] => New arrives
                    [parent] => 1
                )

        )

    [1] => stdClass Object
        (
            [id] => 13
            [name] => Discount
            [parent] => 12
        )

)

But I'm looking for the way to get output:

Array
    (
        [0] => stdClass Object
            (
              [id] => 1
              [name] => Anniversary
              [parent] => 0
            )
        )

        [1] => stdClass Object
            (
               [id] => 12
               [name] => New arrives
               [parent] => 1
            )

        )

        [2] => stdClass Object
            (
                [id] => 13
                [name] => Discount
                [parent] => 12
            )

    )

How can I fix my function?

1

There are 1 answers

0
splash58 On

I don't understand where your array becomes object. If work with array, the code can be

function categoryRecursion($element, $input) {

        $return = array_filter($input, function($v) use ($element) { return $v['id'] == $element; });
        $last   = end($return);
        $str[]  = $last;
        if($last['parent'] !=0) {
            $str = array_merge(categoryRecursion($last['parent'], $input), $str);
        }
        return $str;
}