【发布时间】:2018-09-20 08:09:58
【问题描述】:
我一直在尝试使用 PHP 使用 MySQL 数据创建一个多级嵌套 JSON。
我需要这个 JSON,以便以后可以使用 jQuery 创建 HTML 菜单。
但我目前正在努力创建我的多级嵌套 JSON。我在 Stackoverflow 网站和谷歌上发现了 100 个类似的问题,但它们都略有不同。
基本上,我有一个如下所示的 MYSQL 数据库:
id post_title post_parent
1 test 1 0
2 test 2 1
3 test 3 1
4 test 4 0
5 test 5 3
6 test 6 5
7 test 7 5
post_parent 列是将它们链接在一起的列。
我尝试使用以下 PHP 代码,但 JSON 输出错误。
我当前的 PHP 代码:
$return_arr= array();
$sql = mysqli_query($db_conx,"SELECT * FROM wp_posts WHERE post_status = 'publish' AND post_title !='Hello world!' AND post_title !='' ORDER BY post_title");
while ($row = mysqli_fetch_array($sql ,MYSQLI_ASSOC))
{
if( !isset( $return_arr[ $row['post_parent'] ] ) ) {
$return_arr[ $row['post_parent'] ] = array();
}
if( !isset( $return_arr[ $row['post_title'] ][ $row['post_title'] ] ) ) {
$return_arr[ $row['post_parent'] ][ $row['post_title'] ] = array();
}
}
echo json_encode($return_arr);
上面代码的输出是这样的,这是错误的:
{
"0": {
"test 1": [],
"test 4": []
},
"1": {
"test 2": [],
"test 3": []
},
"3": {
"test 5": []
},
"5": {
"test 6": [],
"test 7": []
}
}
这未显示正确的多级嵌套 JSON 数据。
有人可以就这个问题提出建议吗?
任何帮助将不胜感激。
编辑:
我需要一个像这样结构的多级嵌套 JSON:
[
{
"post_title":"Test 1",
"children":[
{
"post_title":"test 3",
"children":[
{
"post_title":"test 5",
"children":[
{
"post_title":"test 6"
},
{
"post_title":"test 7"
}
]
}
]
},
{
"post_title":"test 2"
}
]
}
]
那么我可以像这样创建一个多级菜单:
https://www.jqueryscript.net/demo/Menu-List-Generator-jQuery-renderMenu/index2.html
【问题讨论】:
-
那么您希望输出是什么?给我们一个例子。如果你不定义什么是对的,那就不好说错了。
-
@ADyson,是的,你是对的,对此感到抱歉。我已经编辑了我的问题。
-
“相似”允许歧义。请根据您显示的相同源数据给出一个示例。否则很难进行任何有意义的比较。
-
@ADyson,编辑了我的问题。