Skip to content
Advertisement

Recursively getting a list of parents for each node in a nested PHP array

In PHP I have a set of nested arrays of data. I want to flatten these, so that for every node and leaf I get a list of its parents.

Here’s an example of the original array – note, each part could be of an unknown depth and length:

JavaScript

(The data I’m actually parsing is this Schema.org JSON file – the above is a minimal example of it.)

And here’s what I’d like to end up with:

JavaScript

I’m assuming I need to recursively call a function to build the array but so far I’m not having much luck. In case this makes it harder, this is happening in a static method.

Advertisement

Answer

Something quick to get you started:

JavaScript

You probably need to add a few checks and comments to make it more readable.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement