jan*_*dor 3 javascript php mysql rest json
下午好,我试图将这些结果放到PHP中的数组中,以便我可以将它们编码为json对象并将它们发送到客户端.查询结果如下所示:
id name hours cat status
3bf JFK Int 24 pass open
3bf JFK Int 24 std closed
3bf JFK Int 24 exp open
5t6 Ohm CA 18 pass closed
5t6 Ohm CA 18 std closed
5t6 Ohm CA 18 std2 open
5t6 Ohm CA 18 exp open
...
Run Code Online (Sandbox Code Playgroud)
我想让json对象看起来像这样:
{ "id": "3bf", "name": "JFK Int", "cats":
{ [ { "cat": "pass", "status": "open" },
{ "cat": "std", "status": "closed" },
{ "cat": "exp", "status": "open" } ] }
{ "id": "5t6", "name": "Ohm CA", "cats":
{ [ { "cat": "pass", "status": "closed" },
{ "cat": "std", "status": "closed" },
{ "cat": "std2", "status": "open" } ],
{ "cat": "exp", "status": "open" } ] }
Run Code Online (Sandbox Code Playgroud)
我已成功连接到mysql并使用平面表使用json_encode导出但这部分我不知道如何在PHP中进行.谢谢.
这是我的代码.这将返回一个json对象数组,但它是平的,而不是嵌套的:
$SQL = "SELECT id, name, hours, cat, status FROM bwt.vewPortCats";
$result = mysql_query($SQL);
$arr = array();
while ($row = mysql_fetch_assoc($result)) {
$arr[] = $row;}
$json = json_encode($arr);
echo $json;
Run Code Online (Sandbox Code Playgroud)
数据本身来自将端口和猫组合在一起的视图.
你能做什么(对不起,不是我写的最好的代码......时间短,想法和精力;-)就是这样的(我希望它仍然传达了这一点):
$SQL = "SELECT id, name, hours, cat, status FROM bwt.vewPortCats";
$result = mysql_query($SQL);
$arr = array();
while ($row = mysql_fetch_assoc($result)) {
// You're going to overwrite these at each iteration, but who cares ;-)
$arr[$row['id']]['id'] = $row['id'];
$arr[$row['id']]['name'] = $row['name'];
// You add the new category
$temp = array('cat' => $row['cat'], 'status' => $row['status']);
// New cat is ADDED
$arr[$row['id']]['cats'][] = $temp;
}
$base_out = array();
// Kind of dirty, but doesn't hurt much with low number of records
foreach ($arr as $key => $record) {
// IDs were necessary before, to keep track of ports (by id),
// but they bother json now, so we do...
$base_out[] = $record;
}
$json = json_encode($base_out);
echo $json;
Run Code Online (Sandbox Code Playgroud)
没有时间对它进行测试或三思而后行,但我希望它能传达出这个想法......