vote up 1 vote down star

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.

flag
This is a duplicate: stackoverflow.com/questions/2053719/… – Mark Jan 23 at 13:28
fwiw, there's some code here that does almost exactly what you're looking for: svn.berlios.de/svnroot/repos/qsf/trunk/qsf/lib/… – Mark Jan 23 at 13:30
Thanks for your answers Mark. I might be missing something because I already went trough the post you suggested and I succeed in generating a multidimensional array but my problem is more related to the correct format for it to be used with the php function json_encode() to be able to pass the data to an AJAX app. – Pierre Jan 23 at 17:27

1 Answer

vote up 2 vote down

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);
link|flag
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 Jan 23 at 17:29

Your Answer

Get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.