MySQL-SELECT转换成特殊数组

时间:2011-08-09 18:42:07

标签: php mysql

我想得到一个像这样的数组:

$autocompletiondata = array(
    3 => 'Hazel Grouse',
    4 => 'Common Quail',
    5 => 'Common Pheasant',
    6 => 'Northern Shoveler',
    7 => 'Greylag Goose',
    8 => 'Barnacle Goose');

退出这个SQL-Query:

SELECT id, name FROM tbl_1

谁能告诉我怎么做?

2 个答案:

答案 0 :(得分:3)

$autocompletiondata = array();

$sql = "SELECT id, name FROM tbl_1";
$result = mysql_query($sql) or die(mysql_error());

while($row = mysql_fetch_assoc($result)) {
   $autocompletiondata[$row['id']] = $row['name'];
}

这假设您已建立与数据库等的连接......

答案 1 :(得分:0)

$autocompletiondata =  array(); 

$query  = "SELECT id, name FROM tbl_1";           
$result = mysql_query($query) or die(mysql_error());

while(list($id, $name) = mysql_fetch_array($result))
{
$autocompletiondata[$id] = $name; 
}

更容易阅读:)