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

1
  • do you know that your query does not contain information about Tens Commented Dec 29, 2013 at 9:25

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah it is working the way I want... But can you please explain how to print it as the above tree structure...?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.