0

I have an stack of randomly sorted elements which all refer to an parent element in this stack (by id, no real reference). The root elements refer to themselves.

What is the most efficient algorithm to get these elements into a nested array like:

array(
  array(
    'element' => $element1,
    'children' => array(
      array(
        'element' => $element1_1,
        'children' => array()
      ),
      array(
        'element' => $element1_2,
        'children' => array()
      )
    ),
  ),
  array(
    'element' => $element2,
    'children' => array()
  )
)

Edit

Data example:

$data = array(
  array('id' => 4, 'pid' => 4, 'value' => 'V1'),
  array('id' => 1, 'pid' => 4, 'value' => 'V2'),
  array('id' => 3, 'pid' => 6, 'value' => 'V3'),
  array('id' => 5, 'pid' => 8, 'value' => 'V4'),
  array('id' => 8, 'pid' => 1, 'value' => 'V5'),
  array('id' => 2, 'pid' => 4, 'value' => 'V6'),
  array('id' => 6, 'pid' => 6, 'value' => 'V7'),
  array('id' => 7, 'pid' => 4, 'value' => 'V8'),
  array('id' => 9, 'pid' => 6, 'value' => 'V9')
);
Inceddy
  • 760
  • 1
  • 6
  • 18
  • Need an example of the elements or data that you're starting with. – Twisty Jun 17 '15 at 19:01
  • Also duplicate of http://stackoverflow.com/questions/8587341/recursive-function-to-generate-multidimensional-array-from-database-result – deceze Jun 18 '15 at 07:20

0 Answers0