douxiao0400 2011-02-28 21:46
浏览 72
已采纳

foreach函数从mysql db创建数组

need to return an array like this for example:

 array(30 => 'Mercedes Benz 310 ',26 => 'Lamborghini Murcielago')

I have a database set up something like this:

CREATE TABLE cars (
  id bigint(20) NOT NULL auto_increment,
  `car_name` tinyint(2) NOT NULL default '0',
  owner varchar(20) NOT NULL default ''
  PRIMARY KEY  (id)
) ENGINE=MyISAM; 

The id need to be the array key.

So I tried to use foreach, but I have still not quite understood how it works.

$q = "select `id`, `car_name` from `cars` where `owner`='$username'";
$result = $conn->query($q); 
unset($q); 

if( !$result){
    return array(0 => 'error'); 
}

$garage = $result->fetch_assoc(); 
$car_id = $garage["id"];
$car_name = $garage["car_name"]; 



foreach( $car_name as $key => $car_id ){

    ...

}
  • 写回答

1条回答 默认 最新

  • dstew32424 2011-02-28 21:51
    关注

    You aren't far off. Something like this should give you the kind of array you're looking for.

        $q = "select `id`, `car_name` from `cars` where `owner`='$username'";
        $result = $conn->query($q); 
        unset($q); 
    
        if( !$result){
            return array(0 => 'error'); 
        }
    
        while($row = mysql_fetch_array($result)){
          $garage[$row['id']] = $row['car_name'];
        }
    
    return $garage;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi