为 jsTree 生成的树

发布于 2024-08-24 08:21:38 字数 671 浏览 7 评论 0原文

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

违心° 2024-08-31 08:21:38

json_encode 不起作用有什么原因吗?

https://www.php.net/json_encode

Is there a reason that json_encode won't work for this?

https://www.php.net/json_encode

浮世清欢 2024-08-31 08:21:38

您可以像这样生成一棵树:

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

You can generate a tree like this:

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文