0

I try to build a multi-dimentionnal array from a simpla array of objects.

Each object contain three properties which can be used th create this array: the ID of the object, the parent ID and the order of displaying for the same depth.

the source array is in this form:

object -> id:1, parent:0, index:2
object -> id:3, parent:0, index:1
object -> id:4, parent:2, index:1
object -> id:2, parent:1, index:1
object -> id:5, parent:0, index:3
...

and the final array have to be in this form:

object -> id:3,         parent:0, index:1
object -> id:1,         parent:0, index:2
object ->     id:2,     parent:1, index:1
object ->         id:4, parent:2, index:1
object -> id:5          parent:0, index:3
...

Of course, there is no limit of depth and a parent can have many children.

I can't create a loop that build this multi-dimentionnal array. I have to find the parent, which can be in any branch, at any depth, if it is already in the array, else I have to add it before attach the current object (the child). It's really hard to me...

Cœur
  • 37,241
  • 25
  • 195
  • 267
blaazzze
  • 142
  • 3
  • 14
  • 1
    This structure looks a lot more like a **tree** than anything "multidimensional". Or perhaps some more general type of graph. – Kerrek SB Nov 06 '11 at 01:01
  • 2
    Extremely similar to [How to create multi-dimensional array from a list?](http://stackoverflow.com/questions/7884337/how-to-create-multi-dimensional-array-from-a-list), just needs additional sorting of each branch. – deceze Nov 06 '11 at 01:08
  • I have really a big problem with my eyes... I haven't found this post. Sorry. It look so easy, I am disappointed to not have finded the solution. Thank you very much, I will test it right now. – blaazzze Nov 06 '11 at 01:14
  • thank you @deceze, with some light modification, it work perfectly. Problem resolved. – blaazzze Nov 06 '11 at 01:57

0 Answers0