2010-07-16 71 views
0

如何使用MySQL數據形成多維數組?我使用這個代碼現在:如何將MySQL數據抓取到多維數組中?

while($row = mysql_fetch_assoc($result)){ 
    $music[$row['artist']][$row['title']][$row['id']][$row['category_id']] = $row['key']; 
} 

而且我認爲這將是更容易使用多維數組來存放我的數據(藝術家陣列=>標題陣列=> ID,CATEGORY_ID,鍵)但我不知道如何使用數據庫中的數據構建一個。我已經使用Google搜索,只能找到靜態/本地數據多維數組的示例,這對我來說並不好。

我也想知道如何在php中輸出多維數據用於實際應用。我會用循環嗎?或者會有另一種方式?

我只想說感謝所有的幫助我已經得到了在stackoverflow,它爲我節省了很多頭痛!

+0

只需注意,這樣做可能是一種昂貴的做法,每次。這可能會更好地構建您的代碼,以便完成您的數據所需的所有工作都發生在循環內部,而無需構建額外的數組。 – 2010-07-16 11:42:56

回答

0
$music = array(); 
while($row = mysql_fetch_assoc($result)){ 
    if (!isset($music[$row['artist']]) { 
     $music[$row['artist']] = array() 
     } 
    $music[$row['artist']][$row['title']]=array('id'=>$row['id'],'category_id'=>$row['category_id'],'key'=>$row['key']; 
    } 

或者更簡單地說,如果內存要求並不是非常重要(我這樣做主要是):

​​

使用兩個換的循環將工作 - 假設你想顯示藝術家的樹,比標題的子樹:

foreach ($music as $artist => $titles) { 
    foreach ($titles as $title => $details) { 
     // do stuff, $details contains all the details for the specific $artist and $title 
     } 
    } 
+0

非常感謝,這正是我一直在尋找的:)。 – user389956 2010-07-16 05:50:44

0
var $music = array() 
while($row = mysql_fetch_assoc($result)) 
{ 
    foreach($row as $k => $v) 
    { 
     $music[$key][] = $v; 
    } 
} 

print_r($music);