2010-03-02 30 views
2

編輯:: 也許我應該問什麼從數據庫中得到結果集的正確方法是。當你有5個連接有1:M的關係時,你是否需要5次不同的時間才能訪問數據庫?陣列幫助。尋找更好的方法

我在一個小時前問過這個問題,但一直沒有找到合適的答案。我繼續寫了一些代碼,但它正是我所需要的,但我正在尋找更好的方法來做到這一點

這個數組給我多行,其中只有一些需要一次而其他需要多次。我需要按照以下所述過濾這些內容,但如果可能的話,希望有更好的方法來做到這一點。

Array 
(
    [0] => Array 
     (
      [cid] => one line 
      [model] => one line 
      [mfgr] => one line 
      [color] => one line 
      [orderid] => one line 
      [product] => many lines 
      [location] => many lines 
     ) 
    [1] => Array 
     (
      .. repeats for as many rows as were found 
     ) 
) 

這段代碼完美地工作,但我認爲有一個更有效的方法來做到這一點。有沒有PHP函數可以讓我清理一下?

// these are the two columns that produce more than 1 result. 
    $product = ''; 
    $orderid = ''; 

    foreach($res as $key) 
    { 
     // these produce many results but I only need one. 
     $cid = $key['cid']; 
     $model = $key['model']; 
     $mfgr = $key['mfgr']; 
     $color = $key['color']; 
     $orderid = $key['orderid']; 

     // these are the two columns that produce more than 1 result. 
     if($key['flag'] == 'product') 
     { 
      $product .= $key['content']; 
     } 
     if($key['flag'] == 'orderid') 
     { 
      $orderid .= $key['content']; 
     } 
    } 

// my variables from above in string format: 

這裏是請求的SQL

SELECT 
cid, 
model, 
mfgr, 
color, 
orderid, 
product, 
flag 
FROM products Inner Join bluas ON products.cid = bluas.cid 
WHERE bluas.cid = 332 
ORDER BY bluas.location ASC 
+0

使用數據庫? – knittl 2010-03-02 10:57:48

+0

是的,結果來自數據庫。 – jim 2010-03-02 10:58:45

+0

使用where語句過濾數據庫... – knittl 2010-03-02 11:09:04

回答

1

沒有看到你的數據庫結構,這是一個有點難以破譯你怎麼竟要處理你的數據。

也許這是你在找什麼?

SELECT p.cid, p.model, p.mfgr, p.color, p.orderid, p.product, p.flag, GROUP_CONCAT(p.content SEPARATOR ', ') 
FROM products AS p 
INNER JOIN bluas AS b ON p.cid = b.cid 
WHERE b.cid = 332 
GROUP BY p.cid, p.flag 
ORDER BY b.location ASC 

所以,現在每個產品cid每個flag將有由逗號的條目分開列表,而不是有這許多人重複每個flag條目。

你用字符串做那麼以後就可以快速把它變成進一步操縱數組做一樣的東西:

explode(', ', $key['content']); 

同樣它真的很難告訴你要拉什麼信息沒有看到你的數據庫結構。你的SQL查詢也不能真正與你的代碼相匹配,就像我甚至沒有看到你抓取content一樣。

無論如何我敢肯定的GROUP BYGROUP_CONCATmore info一些組合是你在找什麼。

如果您可以共享更多的數據庫結構並更詳細地瞭解您準備提取哪些信息以及如何將其格式化,我可以根據需要幫助您使用SQL。