In PHP, I have a structure like this:
Array
(
[0] = Array
(
'id' => 1,
'parent' => 0
)
[1] = Array
(
'id' => 2,
'parent' => 1
)
[2] = Array
(
'id' => 3,
'parent' => 1
)
[3] = Array
(
'id' => 4,
'parent' => 2
)
)
The id
is a unique integer and the parent
is a reference to another element's id
. If parent
is 0, then it has no parent. The tree structure looks like this:
1 -> 2 -> 4
-> 3
(I hope that is clear!). I have been trying to determine an algorithm that will produce a nested array or similar output that exposes the tree hierarchy so I can work with it; for instance one such output would be: tree = ['1' => ['2' => ['4'], '3']]]
. The algorithm could support an array of any arbitrary depth; but I am limiting it on the proviso that a child cannot have more than one parent.
Apologies for the non-standard syntax, I hope it effectively communicates what I'm trying to achieve, which is a depth-first search, I think - however the implementations I've come across are too dry for my understand so I'd appreciate some help with this.