[英]JSON response not as expected using php
我知道這可能是一個非常簡單的問題,但是我找不到這個問題的答案,也許是因為這是一個非常基本的php編程問題。 這是我使用PDO(php)的功能:
<?php
function getAllUsers(){
try {
$conn = getConnection(); //connects to database, no explanation needed... uses PDO
$dbh = $conn->prepare("SELECT * FROM User;");
$dbh->execute();
$users = $dbh->fetchAll(); //<---this is maybe the error
$conn = null;
return $users;
}catch (PDOException $ex){
echo "Error: ".$ex->getMessage();
}
} ?>
當我使用正在實現的API時,會使用其他PHP腳本(使用苗條的框架,仍然可以理解)
<?php
$app->get("/user",function() use($app){
$app->response->headers->set("Content-type","application/json");
$app->response->status(200);
$result = getAllUsers(); //call to my function getAllUsers
$app->response->body(json_encode($result));
});
?>
它工作正常,但我得到的結果是:
[{"idUser":"1","0":"1","userName":"asdasd","1":"asdasd","userPass":"password","2":"password"},{"idUser":"2","0":"2","userName":"2312","1":"2312","userPass":"password","2":"password"}]
而且我認為重復的值"0":"1" , "1":"asdasd" , "2":"password"
不應該存在,但我無法弄清楚如何僅獲取需要而不是重復的值。 任何幫助將不勝感激
我沒有使用PDO,而是使用“常見”的mysql查詢,並且存在相同的問題……您的值翻了一番。 一個數組是關聯數組,另一個是索引數組(0,1,2)。 並且可以通過(如果我還記得的話,則為“ MYSQL_ASSOC”)來僅獲取關聯數組,而無需索引一個。 PDO必須有一些類似的選項。
$ dbh-> fetchAll(PDO :: FETCH_ASSOC);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.