transforming flat php array into multidimensional one based on key value?

Posted by PopRocks4344 on Stack Overflow See other posts from Stack Overflow or by PopRocks4344
Published on 2010-05-11T19:12:13Z Indexed on 2010/05/11 19:14 UTC
Read the original article Hit count: 183

Filed under:
|
|

I have a flat array that I'm trying to make multidimensional. Basically, I want to find the items that have parents and create a subarray for that parent id. Right now (and this is simplified), it looks like this:

Array 
(
  [0] => stdClass Object
  (
    [id] => 1
    [parent] => 0
    [name ] => Parent1
  )

  [1] => stdClass Object
  (
    [id] => 7
    [parent] => 1
    [name] => Child1
  )

  [2] => stdClass Object
  (
    [id] => 9
    [parent] => 1
    [name] => Child2
  )

  [3] => stdClass Object
  (
    [id] => 2
    [parent] => 0
    [name ] => Parent2
  )

  [4] => stdClass Object
  (
    [id] => 88
    [parent] => 2
    [name] => Childof2
  )
)

I'm trying to make this:

Array 
(
  [0] => stdClass Object
  (
    [id] => 1
    [parent] => 0
    [name ] => Parent1
    [children] => stdClass Object
    (
       [1] => stdClass Object
       (
         [id] => 7
         [parent] => 1
         [name] => Child1
       )

       [2] => stdClass Object
       (
          [id] => 9
          [parent] => 1
          [name] => Child2
       )
    )
  )

  [1] => stdClass Object
  (
    [id] => 2
    [parent] => 0
    [name ] => Parent2
    [children] => stdClass Object
    (
       [0] => stdClass Object
       (
         [id] => 88
         [parent] => 2
         [name] => Childof2
        )
    )
  )
)

© Stack Overflow or respective owner

Related posts about php

Related posts about multidimensional