简体   繁体   English

JSON响应未使用php预期

[英]JSON response not as expected using php

I know this is probably a really simple question, but I can't find an answer for this issue, maybe because it is a really basic php programming question. 我知道这可能是一个非常简单的问题,但是我找不到这个问题的答案,也许是因为这是一个非常基本的php编程问题。 This is my function using PDO (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();
    }
} ?>

And when i consume the API that i'm implementing, i use this other PHP script (using slim framework, still pretty understandable) 当我使用正在实现的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));
});
?>

It works fine, but the results that I get are these: 它工作正常,但我得到的结果是:

[{"idUser":"1","0":"1","userName":"asdasd","1":"asdasd","userPass":"password","2":"password"},{"idUser":"2","0":"2","userName":"2312","1":"2312","userPass":"password","2":"password"}]

And I think that the repeated values "0":"1" , "1":"asdasd" , "2":"password" should not be there, but i can't figure out how to get only the data that i want and not the repeated values. 而且我认为重复的值"0":"1" , "1":"asdasd" , "2":"password"不应该存在,但我无法弄清楚如何仅获取需要而不是重复的值。 Any help would be very appreciated 任何帮助将不胜感激

I'm not using PDO, but "common" mysql queries and there is the same...you get doubled your values. 我没有使用PDO,而是使用“常见”的mysql查询,并且存在相同的问题……您的值翻了一番。 One array is associative and other indexed (0,1,2). 一个数组是关联数组,另一个是索引数组(0,1,2)。 And there is option to pass ("MYSQL_ASSOC" if I recall well) to get only associative array, without indexed one. 并且可以通过(如果我还记得的话,则为“ MYSQL_ASSOC”)来仅获取关联数组,而无需索引一个。 There must be some similar option with PDO. PDO必须有一些类似的选项。

$dbh->fetchAll(PDO::FETCH_ASSOC); $ dbh-> fetchAll(PDO :: FETCH_ASSOC);

http://php.net/manual/en/pdostatement.fetchall.php http://php.net/manual/zh/pdostatement.fetchall.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM