1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I was having a long day and recursive functions suddenly became difficult to mentally visualize. With your help I got the job done and have since re-factored into the rest of my project.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.