views:

572

answers:

1

Hi,

I'm retrieving some hierarchical data from an Oracle database using the "connect by" function.

Then I populate a PHP array with the result of my query looking like:

while ($row_branches = oci_fetch_array($query_tree)) {
   $tree[] = array(
     'id' => $row_branches['ID']
   , 'parent' => $row_branche['PARENT']
   , 'data' => htmlspecialchars($row_branches['NAME'])
   , 'level' => $row_branches['LEVEL']
   );
}

The field ID is the unique id of the row The field PARENT is the ID of the parent The field DATA is the name of the item The field LEVEL is the level of the row in the hierarchy.

I'd rather have a multidimensional array because my goal is to use the PHP function json_decode().

The depth of the hierarchy is never known in advance.

So my question is:

How could I populate a multidimensional array with the result of my query?

Thanks a million in advance for your answers.

+2  A: 

try this

function adj_tree(&$tree, $item) {
    $i = $item['ID'];
    $p = $item['PARENT'];
    $tree[$i] = isset($tree[$i]) ? $item + $tree[$i] : $item;
    $tree[$p]['_children'][] = &$tree[$i];
}

$tree = array();
while ($row = oci_fetch_array($query_tree)) {
   adj_tree($tree, $row);
stereofrog
Thanks for your quick reply. It is useful en very clever but unfortunately for some reason I fail to get the correct array format to be used in conjunction with the PHP function json_encode().But thanks again for your help I'll keep digging.
Pierre