<?php

mysql_connect
($db_host,$db_user,$db_password) or die(mysql_error()); 
mysql_select_db($db_name) or die(mysql_error());

// get all menuitems with 1 query
 
$sql "SELECT
            `id`, `parentId`, `order`, `name`
        FROM
            `menu`
        ORDER BY
            `parentId`, `order`"
;
$result mysql_query($sql) or die(mysql_error());

// prepare special array with parent-child relations
$menuData = array(
    
'items' => array(),
    
'parents' => array()
);

while (
$menuItem mysql_fetch_assoc($result)) {

    
$menuData['items'][$menuItem['id']] = $menuItem;
    
$menuData['parents'][$menuItem['parentId']][] = $menuItem['id'];



// menu builder function, parentId 0 is the root
function buildMenu($parentId$menuData)
{
    
$html '';

    if (isset(
$menuData['parents'][$parentId]))
    {
        
$html '<ul>';
        foreach (
$menuData['parents'][$parentId] as $itemId)
        {
            
$html .= '<li>' $menuData['items'][$itemId]['name'];

            
// find childitems recursively
            
$html .= buildMenu($itemId$menuData);

            
$html .= '</li>';
        }
        
$html .= '</ul>';
    }

    return 
$html;
}

function 
buildJSONarray($parentId$menuData) {

    
$aJSON = array();
    if (isset(
$menuData['parents'][$parentId])) {
        
        
$i 0;
        foreach (
$menuData['parents'][$parentId] as $itemId) {

            
$aJSON[$i]["property"]["id"] = "item" $itemId;
            
$aJSON[$i]["property"]["name"] = $menuData['items'][$itemId]['name'];
            
$aJSON[$i]["children"] = buildJSONarray($itemId$menuData);
            
$i++;
        }
    }
    return 
$aJSON;
}

function 
buildJSON($menuData) {

    return 
json_encode(buildJSONarray(0$menuData));
}

if (isset(
$_GET['json'])) {
    
// output json
    
header("Content-type: text/plain");
    echo 
buildJSON($menuData);

} else {

    
//get the menu  (echo it later)
    
$menu buildMenu(0$menuData); 
}
?>