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 ArcGIS批量裁剪
  • ¥15 labview程序设计
  • ¥15 为什么在配置Linux系统的时候执行脚本总是出现E: Failed to fetch http:L/cn.archive.ubuntu.com
  • ¥15 Cloudreve保存用户组存储空间大小时报错
  • ¥15 伪标签为什么不能作为弱监督语义分割的结果?
  • ¥15 编一个判断一个区间范围内的数字的个位数的立方和是否等于其本身的程序在输入第1组数据后卡住了(语言-c语言)
  • ¥15 游戏盾如何溯源服务器真实ip?
  • ¥15 Mac版Fiddler Everywhere4.0.1提示强制更新
  • ¥15 android 集成sentry上报时报错。
  • ¥50 win10链接MySQL