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

时间:2013-03-12 18:15:31

标签: 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'},);
        }

该代码已经产生与“我想要的”相似的结果,但它仍然取代了现有的书籍记录,因此最终每个用户的数组中只有一本书记录。我的问题是:

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

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

3 个答案:

答案 0 :(得分:1)

尝试:

$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'};
    }

这会将您的图书标题指定为数组键/索引,并将评级设置为其值。

答案 1 :(得分:0)

在循环之前添加:

$books[$userID] = array();

在循环内部使用:

$books[$userID][] = array($row{'Book-Title'} => $row{'Book-Rating'},);

答案 2 :(得分:0)

试试这个:

$books[$userID][] = array($row{'Book-Title'} => $row{'Book-Rating'},);