2013-03-12 90 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'},);