1

我正在尝试在 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'},);
        }

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

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

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

4

3 回答 3

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

这会将您的书名分配为数组键/索引,并将评级设置为其值。

于 2013-03-12T18:17:31.557 回答
0

在循环之前添加:

$books[$userID] = array();

在循环内部使用:

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

于 2013-03-12T18:17:31.520 回答
0

试试这个:

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

于 2013-03-12T18:17:43.007 回答