Hey-men-whatsup Hey-men-whatsup - 5 months ago 27
JSON Question

Excluding numbered-index elements of PDO::fetchAll()

$allrows = $pdo->fetchAll(); // select * from ....


I want to transform this
$allrows
into JSON by doing :

echo (json_encode($allrowl,JSON_PRETTY_PRINT));


My problem is that this
fetchAll
will not only extracting data as associate array but also indexed array for each element, hence repeating elements.

[
{
"org_id": "1",
"0": "1",
"category": "A",
"1": "A",

},
{
"org_id": "2",
"0": "2",
"category": "A",
"1": "A",

}
]


Thank you.

Ray Ray
Answer

That's becuase the default fetch mode is FETCH_BOTH. CHange your mode to FETCH_ASSOC and you'll only get the non-numeric keys.

Assuming $pdo is a PDOStatement, set it like this prior to the fetch.

   $pdo->setFetchMode(PDO::FETCH_ASSOC);

You can also set it in the fetch statement:

   $pdo->fetchAll(PDO::FETCH_ASSOC);
Comments