0

I have data in a MYSQL DB that looks like this:

id,parentid,name,count
1,0,top,10
2,1,middle1,5
3,1,middle2,5
4,3,bottom1,3
5,3,bottom2,2

and want to output it via PHP as a heirarchical JSON string where 'top' has a collection of 'middle's etc.

Get my drift? Anyone have a recursive PHP function to help?

2 Answers 2

2

if you've got your data in a PHP array/associative array, then you can use PHP 5.2's JSON functions:

http://www.php.net/manual/en/function.json-encode.php

keep reading on that page to the comments area, they practically give away the code without the fun of figuring it out yourself.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use the function here http://tagarga.com/blok/on/061029 to convert your adjacency list to a nested array, then json_encode() it.

    function adj_tree(&$tree, $item) {
        $i = $item['id'];
        $p = $item['parentid'];
        $tree[$i] = isset($tree[$i]) ? $item + $tree[$i] : $item;
        $tree[$p]['_children'][] = &$tree[$i];
    }

    $tree = array();
    $rs = my_query("SELECT * FROM categories");
    while($row = my_fetch($rs))
        adj_tree($tree, $row);

    echo json_encode($tree[0]);

Comments

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.