我一直试图使用的MySQL数据创建一个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
发布于 2018-04-10 16:35:14
首先,使用所有子程序创建一个数组,并使用post_parent作为索引。在下面的示例中,我调用了这个数组$array_with_elements。之后,您需要一个单独的函数,以便可以使用这个递归函数。
<?php
$array_with_elements = 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)) {
$array_with_elements[$row['post_parent']][] = $row;
}
function add_children($array_with_elements, $wp_level){
$nested_array = array();
foreach($array_with_elements[$wp_level] as $wp_post){
$obj = new stdClass();
$obj->title = $wp_post['post_title'];
$obj->id = $wp_post['ID'];
// check if there are children for this item
if(isset($array_with_elements[$wp_post['ID']])){
$obj->children = add_children($array_with_elements, $wp_post['ID']); // and here we use this nested function again (and again)
}
$nested_array[] = $obj;
}
return $nested_array;
}
// starting with level 0
$return_arr = add_children($array_with_elements, 0);
// and convert this to json
echo json_encode($return_arr);
?>https://stackoverflow.com/questions/49758155
复制相似问题