Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create PHP array from MySQL column

Tags:

arrays

php

mysql

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?

like image 957
Will Peavy Avatar asked Oct 08 '09 14:10

Will Peavy


2 Answers

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

$column = array();

while($row = mysql_fetch_array($info)){
    $column[] = $row[$key];
//Edited - added semicolon at the End of line.1st and 4th(prev) line

}
like image 132
GSto Avatar answered Oct 31 '22 13:10

GSto


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.

like image 23
Tom Haigh Avatar answered Oct 31 '22 13:10

Tom Haigh