2009-10-08 113 views
17

mysql_fetch_array會給我一個獲取行的數組。根據一列中所有行的值生成數組的最佳方法是什麼?從MySQL列創建PHP數組

編輯:很多很好的答案。謝謝大家誰回覆!我最終採用類似於Gumbo和GSto建議的解決方案。我向GSto提供了答案,因爲他的積分較少(只是幫助小傢伙,沒有任何個人特點)。

回答

27

你可以遍歷數組,並創建一個新的,就像這樣:

$column = array(); 

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

} 
4

使用while循環,以獲得記錄,並將其存儲在一個陣列:

$array = array(); 
while ($row = mysql_fetch_array()) { 
    $array[] = $row['column-x']; 
} 
7

沒有功能做到這一點使用mysql擴展,你可以這樣做:

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

獲取數字索引數組中的列顯然要快得多,並且在這裏沒有關聯數組格式的真正好處。

+0

呃,你打我吧。 – 2009-10-08 14:41:08

3

遍歷結果:

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

$columnValues = Array(); 

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

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

} 
0

如果使用PDO而不是PHP的的mysql PDO :: query()的返回值實現了Traversable接口,這意味着你可以使用它與foreach()(不同於你從mysql_query獲得的mysql結果資源)。

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

而如果這些還不夠,你真的,真的需要一個數組(即get_class($ X)===「數組」),還有的fetchAll()方法。

1
// I'm using this for years and it works very good !! it's easy and logic 
$translate = array(); 

while ($row = mysql_fetch_assoc($result)) 
    { 
     $cullomnkey = $row['translshort']; // is what you want the key to be 
     $translate[$cullomnkey] = $row[$language]; // this is the key and the value in the array 
    } 
-1
$query = mysql_query('SELECT * from yourTable'); 
function mysql_field_array($query) { 
    $field = mysql_num_fields($query); 
    for ($i = 0; $i < $field; $i++) { 
     $names[] = mysql_field_name($query, $i); 
    } 
    return $names; 
} 

$fields = mysql_field_array($query); 
$output = implode(',', $fields); //outputs the columns names 
//echo count($fields); //this use if you want count of columns. 
$columns = '{\"fields\":\".json_encode($output).\"}'; 
echo $columns; //for JSON output 
-1

,你可以這樣做:

 $columns = array(); 
     $i=1; 
     while($row = mysql_fetch_array($sql)) 
      { 
       $columns [$i]=$row['value']; 
       $i++; 
      } 
-1

如果您不需要在該表中的其他信息,您可以只查詢你所需要的列,這讓這一切更加容易:

$query = mysql_query("SELECT * FROM table WHERE id='$int' LIMIT 1"); 
$column = array(); 
$column = mysql_fetch_array($query);