PHP将数据库结果添加到多维数组

标签 php mysql database arrays

我正在尝试在 PHP 中生成这样的多维数组:

$books =  array(

    "8" => array(   "my girl" => 2.5, 
                    "the god delusion" => 3.5,
                    "tweak" => 3, "the shack" => 4,
                    "the birds in my life" => 2.5,
                    "new moon" => 3.5),

    "14" => array(    "the last lecture" => 2.5, 
                      "the god delusion" => 3.5,
                      "the noble wilds" => 3, "the shack" => 3.5,
                      "the birds in my life" => 2.5, "new moon" => 1)
     );

来自这样的数据库表:

ID  value   title
------------------------------------------------------------------
8   5   Clara Callan
8   5   Where You'll Find Me: And Other Stories
8   5   The Middle Stories
8   5   Jane Doe
8   6   The Witchfinder (Amos Walker Mystery Series)
8   6   More Cunning Than Man: A Social History of Rats an...
8   7   Goodbye to the Buttermilk Sky
9   6   Beloved (Plume Contemporary Fiction)
12  10  If I'd Known Then What I Know Now: Why Not Learn f...
14  5   Mary-Kate & Ashley Switching Goals (Mary-Kate ...
14  5   Tell Me This Isn't Happening
14  6   Flood : Mississippi 1927
16  9   Airframe
17  7   Death in the Clouds
17  5   Bant/Spec.Last of the Breed
17  6   Piercing the Darkness
17  3   Prophet
19  7   Prague : A Novel

我已经尝试了几种方法,但我仍然无法弄清楚如何做到这一点。我一直在这里搜索许多主题,但仍然没有人讨论这个问题。我是PHP的新手,所以我不太了解PHP中的数组概念。目前我的 PHP 代码是这样的:

        $result = mysql_query($mySelectQuery) or die("<br/><br/>".mysql_error());
        $books = array();
        while ($row = mysql_fetch_array($result)) 
        {
            $userID = $row{'User-ID'};
            $books[$userID] = array($row{'Book-Title'} => $row{'Book-Rating'},);
        }

该代码已经产生了与“我想要的”类似的结果,但它仍然替换了现有的书籍记录,所以最后每个用户的数组中只有一个书籍记录。我的问题是:

我如何用我的查询结果填充一个像我这样格式化的多维数组?

提前一百万感谢您的回答。抱歉英语不好。

最佳答案

尝试:

$result = mysql_query($mySelectQuery) or die("<br/><br/>".mysql_error());
    $books = array();
    while ($row = mysql_fetch_array($result)) 
    {
        $userID = $row{'User-ID'};
        $books[$userID][$row{'Book-Title'}] = $row{'Book-Rating'};
    }

这会将您的书名指定为数组键/索引,并将评级设置为它的值。

关于PHP将数据库结果添加到多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15368963/

相关文章:

php - 在不运行控制台命令的情况下清理缓存的最佳方法是什么?

php - 使用 FFmpeg 提取 FLV 帧 - 支持的格式

php - 使用 while 循环将 db 值存储到 php 数组中?

sql - Postgresql 查询获取一年内每月的计数

php - 使用 PHP (Foreach) 连接两个不同服务器中的两个表

php - 将 php webservice json 响应发送到 javascript

php - 使用php更新mysql不起作用

mysql - 使用 Laravel 5.5 在实时数据库上调用存储过程会引发内存错误

php - 使用 PDO 和 MySQL 确认记录 INSERT

sql - 使用 pg_restore 创建或覆盖表