Skip to content
Advertisement

How to recursively iterate object?

I have instance of this class, which contains an array of several instances of this class. And each of which can contain instances of this class, etc. This class implements the tree model.

JavaScript

I want get all objects model as array structure for JSON representation in future. For that I need recursive iterate all object structure. I can do it simple foreach function with recursive call interate function, but I like to use PHP Interator interfaces, which provides this functional.

How I can do it?

I tried this code, but it didn’t work:

JavaScript

Advertisement

Answer

I’m still not quite sure what you’re trying to do, but here are some examples which might help you (full code below):


Implementing JsonSerializable:

When implementing this interface you’ll be able to control what data will be serialized when json_encode is used on any instance of the class:

JavaScript

Extending RecursiveArrayIterator:

For this to work you only need to extend RecursiveArrayIterator and implement the required methods to work with your Node class:

JavaScript

Extending RecursiveArrayIterator while implementing IteratorAggregate:

An extension to the above could be to also implement IteratorAggregate on Node

JavaScript

Demo: https://3v4l.org/D0GfX

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