在後臺我有REST API,代碼:PHP的while循環代替的foreach得到陣列數據
$app->get('/tasks', 'authenticate', function() {
global $user_id;
$response = array();
$db = new DbHandler();
// fetch task
$result = $db->getAllUserTasks($user_id);
$result = $db->getAllUserTasks($user_id);
if ($result != NULL) {
$response["error"] = false;
$response["id"] = $result["id"];
$response["task"] = $result["task"];
$response["status"] = $result["status"];
$response["createdAt"] = $result["created_at"];
echoRespnse(200, $response);
} else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exists";
echoRespnse(404, $response);
}
});
,並使用此代碼,我從陣列得到的只是第一個數據:
{
error: false
id: 2
task: "Create something"
status: 0
createdAt: "2014-12-01 01:58:42"
}
現在當我想獲取所有數據寫到:
if ($result != NULL) {
foreach ($result as $rez) {
$response["error"] = false;
$response["id"] = $rez["id"];
$response["task"] = $rez["task"];
$response["status"] = $rez["status"];
$response["createdAt"] = $rez["created_at"];
echoRespnse(200, $response);
}
} else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exists";
echoRespnse(404, $response);
}
所以用foreach循環相同的代碼,但然後我得到:Unexpected token {
那有什麼問題?我如何在這裏實現WHILE
循環而不是foreach
???
更新功能:
public function getAllUserTasks($user_id) {
$stmt = $this->conn->prepare("SELECT t.* FROM tasks t, user_tasks ut WHERE t.id = ut.task_id AND ut.user_id = ?");
$stmt->bind_param("i", $user_id);
if ($stmt->execute()) {
$res = array();
$stmt->bind_result($id, $task, $status, $created_at);
// TODO
// $task = $stmt->get_result()->fetch_assoc();
$stmt->fetch();
$res["id"] = $id;
$res["task"] = $task;
$res["status"] = $status;
$res["created_at"] = $created_at;
$item[] = $res;
$stmt->close();
return $item;
} else {
return NULL;
}
}
到底在哪你得到「意外的標記{」? – 2014-12-02 15:40:43
是的,我這樣做對不起,錯在CDE – LaraBeginer 2014-12-02 15:41:04