Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

pdo

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)
like image 774
Jim Avatar asked Oct 27 '11 19:10

Jim


2 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

like image 175
Jaison Erick Avatar answered Oct 14 '22 04:10

Jaison Erick


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)));
like image 40
hakre Avatar answered Oct 14 '22 04:10

hakre