Fetch multi-row, single-column array using Doctrine

Koffeehaus picture Koffeehaus · Dec 4, 2013 · Viewed 9.2k times · Source

I have a Doctrine fetch statement like this

$query = "SELECT id FROM table LIMIT 2";
$result = $db->fetchAll($query);

which returns the array like this:

Array
(
[0] => Array
    (
        [id] => 1
    )

[1] => Array
    (
        [id] => 2
    )
)

Since the only column I fetch is ID, I don't need the array scope do be that deep. Is there a convenient way of making Doctrine return the results in a "flat" array, similar to what what PDO does:

$result = $db->query($query)->fetchAll(PDO::FETCH_COLUMN);

will return

Array
(
    [0] => 1
    [1] => 2
)

Currently I am flattening it using

$result = call_user_func_array('array_merge', array_map("array_values", $result));

Answer

user3802042 picture user3802042 · Jul 28, 2015

You can simply use the PDO functionality (at least if you have MySQL).

$ids = $db
    ->executeQuery($query)
    ->fetchAll(\PDO::FETCH_COLUMN)
;