Skip to content
Advertisement

PHP recursive search and replace array elements

I want to recursively search and replace elements in an array.

The array is tree based so looks like

JavaScript

etc.

I want to be able to replace certain items with other items, so for example, I want to replace all entries in the array (at whatever depth level) of type A with an array of type B. But here’s the catch: The newly replaced objects may also have children of type A that need to be replaced.

So far I’ve got

JavaScript

Which will replace the first level of RefObjects, but will not search the subsequently added children.

I’ve been bashing my head against a wall with this one for hours. Please help!

Cheers, Gaz.

Advertisement

Answer

Put your code into a function and call it again. Pseudocode:

JavaScript

The basics of recursion are to call the same code again…

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