Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP mysql result json_encode return key and index number

Tags:

json

php

Why does the JSON output show both the index number and the association colume name?

I only need just column name such as "UID"

PHP CODE

$res = $statement->fetchAll();
$records = array('Record'=>$posts);
echo json_encode($records);

JSON OUTPUT

{
  "Record":[
    {
      "UID":"1001",
      "0":"1001",
      "NAME":"Robot2",
      "1":"Robot2",
      "EMAIL":"[email protected]",
      "2":"[email protected]",
      "GENDER":"f",
      "3":"f"
    },
    {
      "UID":"1030",
      "0":"1030",
      "NAME":"Anna",
      "1":"Anna",
      "EMAIL":"[email protected]",
      "2":"[email protected]",
      "GENDER":"f",
      "3":"f"
    }
  ]
}

Thanks

like image 559
mohsin.mr Avatar asked Mar 06 '26 06:03

mohsin.mr


2 Answers

See the documentation for an explaination:

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

In order to only get the associative items, you should pass PDO::FETCH_ASSOC to your fetchAll.

like image 171
Layke Avatar answered Mar 08 '26 19:03

Layke


The default fetch style is PDO::FETCH_BOTH, you need to set it to PDO::FETCH_ASSOC.

$res = $statement->fetchAll(PDO::FETCH_ASSOC);

Or you could set the default DEFAULT_FETCH_MODE by:

$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

then you could just do $res = $statement->fetchAll();

like image 35
xdazz Avatar answered Mar 08 '26 19:03

xdazz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!