从嵌套集模型结构为Fancytree创建JSON

时间:2014-11-29 10:14:39

标签: php mysql json fancytree nested-set-model

我想用jquery插件Fancytree显示数据结构。在Google中进行长时间搜索后,似乎在数据库中存储数据结构的最佳方法是嵌套集模型(在此处的Stackoverflow php / Mysql best tree structure中进行了描述)。然而,制作这种结构的相关嵌套JSON非常困难,我无法做到..

这包括转换以下MySQL表:

| category_id |名字| lft | rgt |深度|

| 1 |电子| 1 | 20 | 0 |

| 2 |电视| 2 | 9 | 1 |

| 3 | TUBE | 3 | 4 | 2 |

| 4 | LCD | 5 | 6 | 2 |

| 5 |等离子| 7 | 8 | 2 |

| 6 |便携式电子| 10 | 19 | 1 |

| 7 | MP3播放器| 11 | 14 | 2 |

| 8 | FLASH | 12 | 13 | 3 |

| 9 | CD播放器| 15 | 16 | 2 |

| 10 | 2路无线电| 17 | 18 | 2 |

进入这个JSON:

[{"key": "1", "title": "ELECTRONICS", "expanded": true, "children": [
    {"key": "2", "title": "TELEVISION", "expanded": true, "children": [
        {"key": "3", "title": "TUBE"},
        {"key": "4", "title": "LCD"},
        {"key": "5", "title": "PLASMA"}
    ]},
    {"key": "6", "title": "PORTABLE ELECTRONICS", "expanded": true, "children": [
        {"key": "7", "title": "MP3 PLAYERS", "expanded": true, "children": [{"key": "8", "title": "FLASH"}]},
        {"key": "9", "title": "CD PLAYERS"},
        {"key": "10", "title": "2 WAY RADIOS"}
    ]}
]}]

我想知道是否存在将MySQL数据转换为分层嵌套JSON的简单方法? 谢谢!

1 个答案:

答案 0 :(得分:0)

最后,我设法通过一点一点地制作JSON来使我的树工作。我不认为它是正确的,因为它不是由对象和数组组成,但这似乎工作正常

 <?php 
    if (!isset($DB_connection)) { require_once('../config/_db_connect.php'); } 
    $result = $DB_connection->prepare("SELECT node.category_id, node.name, 
     (COUNT(parent.name) - 1) AS depth FROM nested_category AS node,
      nested_category AS parent WHERE node.lft BETWEEN parent.lft 
      AND parent.rgt GROUP BY node.name ORDER BY node.lft;"); 
    $result->execute(); 

    $i = 0;
    $nb_open = 0;
    $current_level = '';

    echo "[{";
    while( $line = $result->fetch(PDO::FETCH_OBJ) )
    {                       
        if ($current_level == '') { $current_level = $line->depth; } 

        if ($current_level == $line->depth) { if ($i > 0) { echo " }, {"; } }
        elseif ($current_level < $line->depth) {
            echo ',  "children": [ { ';
            $nb_open = $nb_open + 1;
        }
        elseif ($current_level > $line->depth) {
            $nb_to_close = $current_level - $line->depth;
            for ($j = 1; $j <= $nb_to_close; $j++) {
                $nb_open = $nb_open - 1;
                echo " }]";
            }
            echo "}, {";
        }

        echo ' "title": "' . $line->name . '", "key": "' .
              $line->category_id . '", "expanded": true';
        $current_level = $line->depth;
        $i++;
    }

    if ($nb_open>0) { for ($i = 1; $i <= $nb_open; $i++) { echo "}]"; } }
    echo "}]";
    ?>