views:

71

answers:

2

There are simple 2d array with some sort of tree like this:

  • node1
    • node2
      • node3

It's structure is:

array(
    array (
      'id' : 1,
      'pid': 0,
      'title' : 'node1',
      'level' : 1
    ),
    array (
      'id' : 2,
      'pid': 1,
      'title' : 'node2',
      'level' : 2
    ),
    array (
      'id' : 3,
      'pid': 2,
      'title' : 'node3',
      'level' : 3
    ),
)

Is there solutions with PHP to convert this array into:

array(
    array (
      'id' : 1,
      'title' : 'node1',
      'child' :  array (
                   'id' : 2,
                   'title' : 'node2',
                   'child' :  array (
                                 'id' : 3,
                                 'title' : 'node3',
                              ),
                 ),

    )
 ...
)
A: 
<?php
$p = array(0 => array());
foreach($nodes as $n)
{
  $pid = $n['pid'];
  $id = $n['id'];

  if (!isset($p[$pid]))
    $p[$pid] = array('child' => array());

  if (isset($p[$id]))
    $child = &$p[$id]['child'];
  else
    $child = array();

  $p[$id] = $n;
  $p[$id]['child'] = &$child;
  unset($p[$id]['pid']);
  unset($p[$id]['level']);
  unset($child);

  $p[$pid]['child'][] = &$p[$id];    
  // $p[$pid]['child'] = &$p[$id]; // or this, if only one child
}
$nodes = $p['0']['child'];
unset($p);
?>

If each node can only have one child, then replace the one line with $p[$pid]['child'] = &$p[$id];.

(Edit: fixed it to work regardless of how the nodes are sorted.)

konforce
Yeah, i found better solution - http://stackoverflow.com/questions/2094207/php-traversing-function-to-turn-single-array-into-nested-array-with-children-ba
RayZ
A: 

Found @SO PHP Traversing Function to turn single array into nested array with children - based on parent id

$inArray = array(
    array('ID' => '1', 'parentcat_ID' => '0'),
    array('ID' => '2', 'parentcat_ID' => '0'),
    array('ID' => '6', 'parentcat_ID' => '1'),  
    array('ID' => '7', 'parentcat_ID' => '1'),
    array('ID' => '8', 'parentcat_ID' => '6'),          
    array('ID' => '9', 'parentcat_ID' => '1'),  
    array('ID' => '13', 'parentcat_ID' => '7'),
    array('ID' => '14', 'parentcat_ID' => '8'),     
);

function makeParentChildRelations(&$inArray, &$outArray, $currentParentId = 0) {
    if(!is_array($inArray)) {
        return;
    }

    if(!is_array($outArray)) {
        return;
    }

    foreach($inArray as $key => $tuple) {
        if($tuple['parentcat_ID'] == $currentParentId) {
            $tuple['children'] = array();
            makeParentChildRelations($inArray, $tuple['children'], $tuple['ID']);
            $outArray[] = $tuple;   
        }
    }
}

$outArray = array();
makeParentChildRelations($inArray, $outArray);

print_r($outArray);
RayZ