Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why json_encode() return keys values twice (index key and string key)?

When I use the json_encode() function, the method return a Json with two time the same value: one with the string key and one with an index. I did not have this problem before.

$req = $bdd->prepare("SELECT mail,description FROM identifiant WHERE mail = :mail AND pass=:pass");
        if ($req->execute(array(
                    'mail' => $_COOKIE['mail'],
                    'pass' => $_COOKIE['pass']))) {
            header('Content-type: application/json');

            return json_encode($req->fetchAll());

The response:

[
   {
      "mail": "[email protected]",
      "0": "[email protected]",
      "description": "a description",
      "1": "a description"
   }
]

How can I do for don't have index keys ?

like image 987
Anthony Avatar asked Oct 09 '13 09:10

Anthony


People also ask

What does json_encode return?

Syntax. The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.

What does the PHP function json_encode () do?

The json_encode() function is used to encode a value to JSON format.

What is json_encode in Javascript?

json_encode(mixed $value , int $flags = 0, int $depth = 512): string|false. Returns a string containing the JSON representation of the supplied value . If the parameter is an array or object, it will be serialized recursively.

What is a JSON encoded string?

The method JSON. stringify(student) takes the object and converts it into a string. The resulting json string is called a JSON-encoded or serialized or stringified or marshalled object.


2 Answers

Use PDO::FETCH_ASSOC fetching mode:

return json_encode($req->fetchAll(PDO::FETCH_ASSOC));
like image 128
Marek Avatar answered Sep 18 '22 12:09

Marek


It's not json_encode, it's because your PDO instance's fetch mode is set to PDO::FETCH_BOTH. See the documentation for PDOStatement::fetchAll's fetch style.

like image 25
deceze Avatar answered Sep 18 '22 12:09

deceze