Question

I have a 1 to 1 linear tree where languages => types => products => etc; with languages having many types and types having many products and so on.

I have written a recursive function to return an array in the following style:

Array
(
    [0] => Array
    (
        [id] => 166
        [name] => product1
        [type] => product
        [depth] => 2
        [parent] => Array
            (
                [0] => Array
                    (
                        [id] => 165
                        [name] => default
                        [type] => type
                        [depth] => 1
                        [parent] => Array
                            (
                                [0] => Array
                                    (
                                        [id] => 1
                                        [name] => en
                                        [type] => language
                                        [depth] => 0
                                        [parent] => false

                                    )

                            )

                    )

            )

    )

)

What I want is a recursive method that will traverse that tree and provide an array such as

[0] => array( 'id' => 1, 'name' => 'en'),
[1] => array( 'id' => 165, 'name' => 'default'),
[2] => array( 'id' => 166, 'name' => 'product1')

With 0,1,2 being equal to that elements depth this is so I can build breadcrumbs of the data.

Thank you.

Was it helpful?

Solution

The key here is to make a print function that you'll be able to call recursively. I'd suggest something like this

function print_recursive($array, $depth = 0) {
    //Code to print your stuff

    //Calls the print function on the parent if it's an array
    if(is_array($array['parent'])) {
        print_recursive($array['parent'], $depth+1);
    }
}

The depth parameter is 0 by default but we increment it by 1 when calling print_recursive on $array['parent']. This way, each time you get deeper in the array, it'll get incremented.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top