phparraysjsonpdojsonencode

Create json-encoded array from a PDO query result column


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"]

Solution

  • 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