satishgaudo.com

Understanding technology

Script to Generate an array of hierarchical node tree

Consider the file “list.txt” below containing two columns
parent id and child id separated by “space” on each row

That is the source for data for computation:

list.txt

0 1
1 2
2 3
0 4
4 5
0 6
6 7

Below is the script for getting an array of the hierachical node tree

tree.php

<?

$l = file(”./list.txt”);

$list = array();

for ($i = 0;$i < count($l); $i++)

{

list($list[$i][parent],$list[$i][child]) = explode(” “,trim($l[$i]));

}

$list = getChildList($list);

$tree = getNodeTree();

print_R($tree);

function getChildList($list) {

$normList = array();

for ($i = 0;$i < count($list); $i++)

{

$normList[$list[$i][parent]][] = $list[$i][child];

}

return $normList;

}

function getNodeTree($child=0) {

global $list;

if (count($list[$child])==0) {

return;

}

foreach ($list[$child] as $k=>$v)

{

$tree[$v] = getNodeTree($v);

}

return $tree;

}

?>

Output of the script:

Array
(
    [1] => Array
        (
            [2] => Array
                (
                    [3] =>
                )

        )

    [4] => Array
        (
            [5] =>
        )

    [6] => Array
        (
            [7] =>
        )

)
Bookmark and Share
Categories: PHP
*