how to convert a path enumeration tree table to Array in PHP?

279 Views Asked by At

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)?

0

There are 0 best solutions below