2009-12-11 66 views
0

我在數據庫中有一些行代表銷售中的訂單項。每個訂單項有五列:在PHP中分組相關項目

  • id:主鍵。
  • sale_id:此訂單項所屬的銷售額(Sales表的外鍵)。
  • product_id:此項目對應的產品(Products表的外鍵)。
  • group:此項目所屬的行項目組。
  • is_subitem:此訂單項是否爲子項目。對於具有相同group值的任何一組訂單項,這裏保證只有一個「假」值。

我想在遍歷所有行特定sale_id生產,其中一個列表:

  • 具有相同group值線項目爲關聯在一起
  • 行項目與is_subitem == false組首先出現

如何創建一個數據結構來促進這一點並按照我想要的方式進行迭代?

回答

1

像這樣的東西可能會工作..我還沒有測試過。


$data = array(); 
$result = mysql_query($your_query_here); 

while($row = mysql_fetch_assoc($result)) 
{ 
    if(!isset($data[$row['group']])) 
    { 
     $data[$row['group']] = array(); 
    } 

    if(false == $row['is_subitem']) 
    { 
     // when subitem is false we put the item at at the front of the array by unshifting it. 
     array_unshift($data[$row['group']], $row); 
    } 
    else 
    { 
     // else we just add the row to the end. 
     $data[$row['group']][] = $row; 
    } 
} 
0

我編輯了上面的幾次,但現在應該是相當不錯的。

+0

沒有必要爲這個評論創建一個新的答案。把它放到你編輯的答案中。順便說一句'上面'變得不必要,如果你按'最新'排序的答案;) – 2009-12-11 18:00:56

+0

謝謝菲利克斯 - 我是新的。 – Anon 2009-12-11 18:06:40