为jsTree生成的树

时间:2010-03-05 11:25:00

标签: php jstree

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;
}

2 个答案:

答案 0 :(得分:2)

有没有理由说json_encode不能用于此?

http://us3.php.net/json_encode

答案 1 :(得分: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;
}