-2

I am creating a json array with data from mysql:

$array = $db->query("SELECT ...")->fetchAll(PDO::FETCH_ASSOC);
print json_encode($array);

This returns:

[{"animal":"alpaca"},{"animal":"buffalo"},{"animal":"cat"},{"animal":"tiger"}] 

But I need it to return data with the following syntax:

 ["alpaca","buffalo","cat","tiger"]
2
  • Need to change FETCH_ASSOC because it returns associative array Commented Sep 22, 2015 at 11:56
  • 1
    or print json_encode(array_values($array));
    – Federkun
    Commented Sep 22, 2015 at 11:56

2 Answers 2

1

Use array_values() for your issue:

$array = json_encode(array_values($array));
1
  • This returns [{"animal":"alpaca"},{"animal":"tiger"}]
    – TheG
    Commented Sep 22, 2015 at 12:04
0

As you can simply use array_values over here but for an alteration you can also use array_column like as

$array = $db->query("SELECT .............")->fetchAll(PDO::FETCH_ASSOC);
print json_encode(array_column($array,'animal'));

Note: array_column() requires PHP > 5.5.0

Not the answer you're looking for? Browse other questions tagged or ask your own question.