2013-03-12 56 views
1

我试图生成PHP多维数组是这样的:从数据库表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'},); 
     } 

该代码已经产生了“我想要什么”类似的结果,但它仍然取代现有的书中记载,所以最后每个用户只有在有一本书记录了阵列。我的问题是:

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

非常感谢您的回答。对于糟糕的英语感到抱歉。

回答

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

这将赋予你的书名为数组键/指数,并设定评价,因为它的价值。

+0

谢谢,它的工作! – 2013-03-13 12:05:31

0

循环加载之前:

$books[$userID] = array();

里面的循环利用:

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

0

试试这个:

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