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条)

报告相同问题?

悬赏问题

  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用