Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
    
do you know that your query does not contain information about Tens –  user1625871 Dec 29 '13 at 9:25

1 Answer 1

up vote 0 down vote accepted

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);
share|improve this answer
    
Yeah it is working the way I want... But can you please explain how to print it as the above tree structure...? –  user2958359 Dec 29 '13 at 9:32
    
Look here- stackoverflow.com/questions/13002327/… –  sergio Dec 29 '13 at 9:38

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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