dongluxin2452 2014-03-26 00:51
浏览 143
已采纳

SQL查询的多维数组

I have an multi-dimensional array that I am trying to build from an SQL query. I am having trouble adding the id in the inner array.

Code:

$checkboxes = "SELECT id, name FROM review_sites WHERE active=1 ORDER BY name ASC"; 
$result = mysql_query($checkboxes) or die(mysql_error());
$names = array();

while ($row = mysql_fetch_array($result)) {
    $names[]['name'] = $row['name'];

}

Currently the Array looks like:

Array
(
[0] => Array
    (
        [name] => 411.ca
    )

[1] => Array
    (
        [name] => AutoMD
    )

I Need the array to look like this:

Array
(
[0] => Array
    (
        [id] => 4
        [name] => 411.ca
    )

[1] => Array
    (
        [id] => 9
        [name] => AutoMD
    )
  • 写回答

2条回答 默认 最新

  • doujiu8145 2014-03-26 00:53
    关注

    You are only selecting id and name in the query so, in the loop:

    while ($row = mysql_fetch_assoc($result)) {
        $names[] = $row;
    }
    

    Or simply:

    while ($names[] = mysql_fetch_assoc($result)) {}
    

    Notice, mysql_fetch_assoc() to only return an associative array. mysql_fetch_array() returns an associative and numerically indexed array.

    Also:

    This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include: mysqli_fetch_array() PDOStatement::fetch()

    If you were to use the MySQLi extension then you may be able to use:

    $names = mysqli_fetch_all($result, MYSQLI_ASSOC);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?