Home » Php » In PHP, is it possible to get a 1 dimmensional array using PDO?

In PHP, is it possible to get a 1 dimmensional array using PDO?

Posted by: admin July 12, 2020 Leave a comment

Questions:

This seems like it should be (and probably is) trivial. I have a simple query:

SELECT Name From User;

When I run the query using this code:

$rows = $preparedStatement->fetchAll(PDO::FETCH_ASSOC);

$Rows looks like this:

Array ( [0] => Array ( [Name] => Doug ) [1] => Array ( [Name] => John ) )

Is there an easy way to make the array look something like this:

Array( Doug, John)
How to&Answers:

Using the constant PDO::FETCH_COLUMN:

$columnNumber = 0;
$rows = $preparedStatement->fetchAll(PDO::FETCH_COLUMN, $columnNumber);

This way you’ll get exactly what you proposed.

You can also do the following:

$columnNumber = 0;
$rows = $preparedStatement->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_UNIQUE, $columnNumber);

This way you’ll get an array with unique values.

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

Answer:

I think the right answer has been given by Jaison Erick, in case you need to flatten what you’ve got returned (not really recommended), this would do it:

$flat = reset((call_user_func_array('array_merge_recursive', $rows)));