我有以下PHP代码访问数据库函数,获取响应并将其编码为JSON。
它应该创建一个错误对象,然后是一个包含所有返回的数据库行的数组。
$key = $db->getKeyPermissions();
if ($key != false) {
$response["error"] = FALSE;
for($i = 0; $i < count($key); $i++){
$response["key"] = array();
$response["key"]["endpoint_description"] = $key[$i]["endpoint_description"];
$response["key"]["live"] = $key[$i]["live"];
$response["key"]["activity_name"] = $key[$i]["activity_name"];
}
echo json_encode($response);
而不是回显大约13个项目的列表,它只回显最后一个项目作为对象。我究竟做错了什么?如何转动&#34;键&#34;将对象放入包含所有键的列表中。
这是JSON输出。
{
"error": false,
"key": {
"endpoint_description": "Guilds' rosters, history, and MOTDs for all guilds you are a member of.",
"live": 0,
"activity_name": ""
}
}
我相当确定这是它应该是什么样子,我需要它。
{
"error": false,
"key": [
{
"endpoint_description": "Guilds' rosters, history, and MOTDs for all guilds you are a member of.",
"live": 0,
"activity_name": ""
},
{
"endpoint_description": "Guilds' rosters, history, and MOTDs for all guilds you are a member of.",
"live": 0,
"activity_name": ""
},
{
"endpoint_description": "Guilds' rosters, history, and MOTDs for all guilds you are a member of.",
"live": 0,
"activity_name": ""
}
]
}
答案 0 :(得分:1)
$key = $db->getKeyPermissions();
if ($key != false) {
$response["error"] = FALSE;
for($i = 0; $i < count($key); $i++){
$response["key"][$i] = array();
$response["key"][$i]["endpoint_description"] = $key[$i]["endpoint_description"];
$response["key"][$i]["live"] = $key[$i]["live"];
$response["key"][$i]["activity_name"] = $key[$i]["activity_name"];
}
echo json_encode($response);
这应该按预期工作[$ i]。根据您的要求,用法可以像
$响应[&#34;键&#34;] [$ i]于
请检查
答案 1 :(得分:0)
$key = $db->getKeyPermissions();
if ($key != false) {
$response["error"] = FALSE;
$response["key"] = array();
for($i = 0; $i < count($key); $i++){
$response["key"][] = [
"endpoint_description" => $key[$i]["endpoint_description"],
"live" => $key[$i]["live"],
"activity_name" => $key[$i]["activity_name"]
];
}
echo json_encode($response);