tags:

views:

406

answers:

6

mysql_fetch_array will give me an array of a fetched row. What's the best way generate an array from the values of all rows in one column?

Edit: Lots of great answers. Thank you everyone who replied! I ended up going with a solution similar to what Gumbo and GSto suggested. I gave the answer points to GSto because he has less points (just helping out the little guy, nothing personal).

+2  A: 

Use a while loop to get the records and store them in an array:

$array = array();
while ($row = mysql_fetch_array()) {
    $array[] = $row['column-x'];
}
Gumbo
+4  A: 

There is no function to do this using the mysql extension, you can do this:

$result = array();
while ($row = mysql_fetch_array($r, MYSQL_NUM)) {
    $result[] = $row[0];
}

It is apparently marginally faster to fetch the columns in a numerically indexed array, and there is no real benefit here to having the associative array format.

Tom Haigh
Eh, you beat me to it.
The Wicked Flea
+5  A: 

you could loop through the array, and create a new one, like so:

$column = array()

while($row = mysql_fetch_array($info)){
    $column[] = $row[$key]
}
GSto
+2  A: 

Loop through the result:

$result = mysql_query(...);
$data = array();
while ($row = mysql_fetch_array($result)) {
    array_push($data, $row["columnyouwant"]);
}
Dominic Rodger
A: 
$result = myslq_query("SELECT columnname FROM table WHERE x=y");

$columnValues = Array();

while ( $row = mysql_fecth_assoc($result) ) {

  $columnValues[] = $row['columnname']

}
code_burgar
A: 

If you use PDO instead of php-mysql the return value of PDO::query() implements the Traversable interface, meaning you can use it e.g. with foreach() (unlike the mysql result resource you get from mysql_query).

foreach( $pdo->query('SELECT x,y,z FROM foo') as $row ) {

And in case this does not suffice and you really, really need an array (i.e. get_class($x)==='Array'), there's the fetchAll() method.

VolkerK