0

Following is a mysql table named "readcontent_categories"

enter image description here

I want to produce a tree of indefinite depth using the above table. For example let I want to see everything under "english". Then it must show as below:

english
  |--------+Tens
              |-------+present
              |-------+past
              |-------+future

Now I tried as below :

<?php
        include("config.php");

        $query = "SELECT * FROM readcontent_categories";
        $result = mysql_query($query);

        function getChildren($pid){
                $r = array();
                global $row, $result;
                while( $row = mysql_fetch_array($result) ){
                    if($row['parent_id'] == $pid)$r[$row['id']] = getChildren($row['id']);
                }

            return $r;
        }

        $final = getChildren(1);
        print_r($final);


    ?>

So am I doing it write? How can I get an output as above ? The output I am getting is not as expected. My output is as below:

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

But how can the above output is obtained? Anybody can help???

user2958359
  • 121
  • 1
  • 7
  • 15
  • do you know that your query does not contain information about Tens –  Dec 29 '13 at 09:25

1 Answers1

0

Use this custom function: for example:

$items = array(
        array('id' => 42, 'parent_id' => 1),
        array('id' => 43, 'parent_id' => 42),
        array('id' => 1,  'parent_id' => 0),
);

function buildTree($items) {

    $childs = array();

    foreach($items as &$item) $childs[$item['parent_id']][] = &$item;
    unset($item);

    foreach($items as &$item) if (isset($childs[$item['id']]))
            $item['childs'] = $childs[$item['id']];

    return $childs[0];
}

$tree = buildTree($items);
sergio
  • 5,210
  • 7
  • 24
  • 46