我一直在寻找尝试拼凑我的解决方案的日子,但我仍在苦苦挣扎。我正在努力使用一些PHP并将其变成json-encode中我想要的格式,所以我可以使用knockout.js。
我有一个看起来像这样的数据库:
| id | name | value |
| 1 | taskName | First Task |
| 1 | taskDetail | Enter your first task |
| 1 | taskList | Very Important |
| 2 | taskName | Second Task |
| 2 | taskDetail | Enter your second task |
| 2 | taskList | Important |
我正在尝试使用json_encode将此响应发送到我的网站,如下所示:
[
{
"id": "1",
"taskName": "First Task",
"taskDetail": "Enter your first task",
"taskList": "Very Important"
},
{
"id": "2",
"taskName": "Second Task",
"taskDetail": "Enter your second task",
"taskList": "Important"
}
]
这是我到目前为止所做的:
$user = 1;
$task_sql = "
SELECT *
FROM `li_id`
INNER JOIN `li_details`
ON li_id.id = li_details.id
WHERE li_id.user = '" . $user . "'";
$result = mysql_query($task_sql, $con);
$results = array();
while ($row = mysql_fetch_assoc($result)) {
$results[] = array($row['name'] => $row['value']);
}
echo json_encode($results);
响应:
[
{
"taskName": "First Task"
},
{
"taskDetail": "Enter first task in application."
},
{
"taskList": "Important"
},
{
"taskName": "Second Task"
},
{
"taskDetail": "Enter second task in application."
},
{
"taskList": "Very Important"
}
]
问题在于我无法弄清楚如何将id分组到单独的数组中。我尝试过几件事,但没有运气。任何提示或指向其他线程都会很棒。谢谢!
答案 0 :(得分:1)
这样的事情怎么样:
while ($row = mysql_fetch_assoc($result))
{
if (!isset($results[$row['id']])) $results[$row['id']] = array();
$results[$row['id']][$row['name']] = $row['value'] );
}
然后在json_encode之后,你将把所有字段嵌套在他们的id
中