I was wondering if it’s possible to do something like this.
I’m having the following string:
Parent1@MiddleA%Child|Child|Child|MiddleB%Child|Child|Child|Parent2@MiddleA%|Child
And I’d like to explode it into something like:
-Parent1
---MiddleA
------Child
------Child
------Child
---MiddleB
------Child
------Child
------Child
-Parent2
---MiddleA
------Child
I don’t understand how to explode it and then explode it again to create an output like above.
The idea is that every parent will be identified with a trailing @, every child of that parent will have a trailing % and every child of that child will have a trailing|.
The data you give as input in your question:
is not really well fitting to produce the output you ask for. It’s even syntactically incorrect at it’s end, the delimiters in
MiddleA%|Childspecifically.Correnting this, you can easily do it with
preg_split:If you don’t have the input string in a valid format, you need to fix it first, e.g. with an appropriate parser or you need to react on the bogus cases inside the foreach loop.
Edit: This is an modified example that turns the string into a tree-like structure so you can output it with nested
foreachloops:(Demo) – Hope this is helpful.