【发布时间】:2012-10-31 10:48:10
【问题描述】:
我一直在纠结这个问题,看起来很简单。我正在尝试使用 PHP/MYSQL 生成一个菜单/子菜单 json:这些是表:
CREATE TABLE `menuHome`
`id`,
`titleName`
CREATE TABLE `menu`
`id`,
`parentmenu`,
`name`
'menuHome' 将有 'titleName' 例如 'About Us' 通过 'parentmenu' 在 'menu' 上加入 'id' 这将有多个条目,例如 'history'、'Owners'、'News'。
我想要实现的结构是:
`
{
"menu" : {
"sections" : [
{
"title" : "About Us",
"items" : [
{
"name" : "History",
"id" : "0909"
},
{
"name" : "Owners",
"id" : "0910"
},
{
"name" : "News",
"id" : "0916"
}
]
},
{
"title" : "Contact Us",
"items" : [
{
"name" : "Address",
"id" : "0949"
},
{
"name" : "Map",
"id" : "0978"
}
]
},
{
"title" : "Products",
"items" : [
{
"name" : "Jeans",
"id" : "1010"
},
{
"name" : "Tables",
"id" : "1088"
},
{
"name" : "Shoes",
"id" : "2424"
}
]
}
]
}
}
`
我已经尝试过,虽然,对于,对于很多配置中的每一个,但我无法让它构建正确的数组结构来编码为 json。我现在处于代码盲区阶段,所以任何帮助都会得到很大的帮助
这是我最后一次尝试:
$sql_query = 'SELECT menuHome.titleName, menuHome.id FROM menuHome';
$result = $mysqli->query($sql_query);
$menu = array();
while ($row = $result->fetch_assoc()) {
$menuid = $row["id"];
$sql_query2 = 'SELECT menu.name, menu.id FROM menu WHERE menu.parentmenu = "' . $menuid . '"';
$result2 = $mysqli->query($sql_query2);
while ($row2 = $result2->fetch_assoc()) {
$menu[$row["titleName"]][] = $row2;
}
}
return json_encode($menu);
这是上面带来的结果:
{
"About Us" : [
{
"name" : "History",
"id" : "1"
},
{
"name" : "Owners",
"id" : "2"
},
{
"name" : "News",
"id" : "3"
}
],
"Contact Us" : [
{
"name" : "Address",
"id" : "4"
},
{
"name" : "Map",
"id" : "5"
}
],
"Products" : [
{
"name" : "Jeans",
"id" : "6"
},
{
"name" : "Tables",
"id" : "7"
},
{
"name" : "Shoes",
"id" : "8"
}
]
}
问题是我无法事先获得“对” - “title” = “About us”...这很简单,但我对这个问题已经脑残了。
我可以在 json_encode 之前添加这个:
$menuoutput = array("menu" => array("sections" => array($menu)));
但是如何在“关于我们”之前显示“key”“titleName”或只是“title”...
【问题讨论】:
-
显示你尝试了什么
-
别忘了你可以把它编译成php
array然后用json_encode()把它转换成json字符串。 -
请显示你在 json_encode 之后得到了什么输出,比如
var_dump(json_encode($menu))。