2010-03-05 39 views
1
function createJsonTree($array, $currentParent, $currLevel = 0, $prevLevel = -1) { 

foreach ($array as $categoryId => $category) { 

    if ($currentParent == $category['parent']) {  

    if ($currLevel > $prevLevel) $output .= ' , "children":[ '; 

    if ($currLevel == $prevLevel) $output .= " }, "; 

    $output .= '{ "data" :'.'"'.$category['menu_title'].'"'; 

    if ($currLevel > $prevLevel) { $prevLevel = $currLevel; } 

    $currLevel++; 

    $output .= self::createJsonTree($array, $category['id'], $currLevel, $prevLevel); 

    $currLevel--;  
    } 

} 

if ($currLevel == $prevLevel) $output .= " }] "; 
return $output; 
} 
+3

你需要解釋一下你的問題的更多細節。發佈標題和代碼牆並不便於我們幫助您。你想做什麼,你做了什麼,你現在做什麼與你想做的不同? – Marius 2010-03-05 11:28:07

回答

1

您可以生成這樣的樹:

function createTree() 
{ 
    $sql = "SELECT id, parent_id, title FROM category order by id "; 
    $filas = UtilConexion::$pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC); 
    $arbol = '{"data":[{"attr":{"id":"000"},"data":"Nodo raíz","state":"open"' . 
    $this->createJsonTree($filas, null) . '}]}'; 
    return $arbol; 
}