2

I created a tree table by path enumeration structure in mysql database. Here is my table:

+----+----------+-----------+-----------+
| id | name     | path      | id_parent |
+----+----------+-----------+-----------+
|  1 | node1    | /1/       | -1        |
|  2 | node2    | /1/2/     | 1         |
|  3 | node3    | /3/       | -1        |
|  4 | node4    | /3/4/     | 3         |
|  5 | node5    | /3/4/5/   | 4         |
+----+----------+-----------+-----------+

Now I want to convert it to Array in php, like this:

$tree = [
    {
        name: 'node1', id: 1,
        children: [
            { name: 'node2', id: 2 }
        ]
    },
    {
        name: 'node3', id: 3,
        children: [
            { 
                name: 'node4', id: 4 ,
                children: [
                    { name: 'node5', id: 5 }
                ]
            }
        ]
    }
]

The below function works fine but it is heavy for big data:

function createTreeDocs($idnode) {
    global $CON;
    $Q = "SELECT ID,NAME,PATH FROM documents where ID_PARENT={$idnode} order by PATH asc";
    $RES = $CON -> query( $Q );
    $NUM = $CON -> num( $RES );
    $tree = array();
    for ($i=0 ; $i<$NUM ; $i++) {
        $ROW = $CON -> fetch( $RES );
        $node = array("name"=> $ROW["NAME"], "id"=> $ROW["ID"]);
        $childs = createTreeDocs($ROW["ID"]);
        if (sizeof($childs)>0)
            $node["children"] = $childs;
        array_push($tree,$node);
    }
    return $tree;
}
print_r(createTreeDocs(-1));

(I want to use it for jqTree plugin). How can I do this without using recursive functions in php (just by a loop)?

Nic3500
  • 8,144
  • 10
  • 29
  • 40
saleh mosleh
  • 135
  • 1
  • 14
  • What about [leveraging the database](https://stackoverflow.com/questions/18106947/cte-recursion-to-get-tree-hierarchy)? Did you mean: [recursion](https://www.google.com/search?q=recursion) :) You probably do want to make use of it... – ficuscr May 30 '18 at 17:15
  • @ficuscr , yes recursion. – saleh mosleh May 30 '18 at 17:18
  • @ficuscr , no i want to use PATH enumeration , look at [this](http://www.waitingforcode.com/mysql/managing-hierarchical-data-in-mysql-path-enumeration/read). – saleh mosleh May 30 '18 at 17:24

0 Answers0