Skip to content
Advertisement

PHP recursive array copy

I have a multidimensional array of arrays (source below), where my keys and values are arbitrary strings. I want to create a new array (desired below), where the hierarchy stays the same, but every KEY is restructured into its own array, with the key itself becoming a ‘title’ value, and any subarrays are continued under ‘children’.

How can I accomplish this using a recursive function that takes &$source and &$destination arrays, and populates the destination array accordingly?

Source Array:

JavaScript

Desired Array:

JavaScript

Note: I don’t care about the final nodes/leafs in my new array.

Advertisement

Answer

You can do te conversion without passing a reference to the destination array.

JavaScript

Codepad example

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