2010-10-11 71 views
1

我有以下代碼:MySQL和PHP - For Each?

SELECT q21, q21coding AS Description FROM `tresults_acme` WHERE q21 IS NOT NULL AND q21 <> '' ORDER BY q21coding 

它帶回以下(節選):

Text              Description 
Lack of up to date equal pay cases&legislation - t... Content needs updating 
The intranet could contain more "up to date traini... Content needs updating 
Poorly set out. It is hard to find things.   Difficulty in navigating/finding content 
Only use the intranet as a necessity. Will ask my ... Difficulty in navigating/finding content 

現在,我想在一個PHP頁面上表中顯示此但我有一些因爲我想顯示它的方式的問題,它需要如下:

Content needs updating 
---------------------- 
[List all the comments relating to this description] 

Difficulty in navigating/finding content 
---------------------------------------- 
[List all the comments relating to this description] 

等等。

現在我認爲這是一個PHP中的For Each循環,但是我的頭腦很糟糕 - 任何想法和建議都非常受歡迎!

感謝,

+0

外觀上的jqGrid顯示此表+搜索和編輯開始看:http://www.trirand.net/demophp.aspx – 2010-10-11 09:25:51

回答

2

簡單的方法

  1. 設置prev_descNULL
  2. 對於每一行打印text
  3. 如果description不等於prev_desc在前面加上了新的 「節」 的說明並設置爲prev_desc <- description

E.g. (未經測試!),

$prev_desc = null; 
while ($row = mysql_fetch_assoc(...)) { 
    if ($prev_desc != $row['description']) { 
     print '<h1>' . $row['description'] . '</h1>'; 
     $prev_desc = $row['description']; 
    } 
    print $row['text'] . '<br />'; // Formatting needed 
} 

注意:您必須保持ORDER BY <description-column>纔能有行 「分組」。否則,這種簡單的方法將無法工作。

演示,具體做法

我可以考慮更「乾淨」創造某種2D容器,以「分類」所提取的數據,例如,

$items = array(
    'Content needs updating' => array(
     'Lack of ...', 
     'The intra...' 
    ), 
    ... 
); 

然後你可以遍歷這些項目像這樣:

foreach ($items as $desc => $texts) { 
    print '<h1>' . $desc . '</h1>'; 
    foreach ($texts as $text) { 
     print $text . '<br />'; 
    } 
} 

正如@bobince指出的那樣,確保直接進入最終HTML的內容能夠正確轉義, htmlspecialchars()

+0

優秀 - 謝謝! – 2010-10-11 09:41:33

+0

爲了避免HTML注入問題,當插入到HTML時,請記得在描述中使用'htmlspecialchars()'(如果不是HTML標記,則使用文本)。 – bobince 2010-10-11 10:04:25

+0

@bobince好點,會編輯。 – jensgram 2010-10-11 10:19:53

0

你只需要跟蹤你最後顯示的標題。我不知道你正在使用的數據庫訪問的庫,那麼您如何訪問列細節/行會略有不同,但在這裏它是僞那種-的:

$lastHeading = ''; 
foreach($rows as $row) 
{ 
    if ($lastHeading != $row['Description']) 
    { 
     if ($lastHeading != '') 
      echo '</ul>'; 

     $lastHeading = $row['Description']; 
     echo "<h1>$lastHeading</h1>"; 
     echo '<ul>'; 
    } 

    echo '<li>'.$row['Text'].'</li>'; 
} 
if ($lastHeading != '') 
    echo '</ul>'; 

這樣做的在<ul>中添加註釋的功能,不確定是否需要您的註釋。

這可以工作,因爲您已按「說明」列排序。這意味着你知道所有具有相同「描述」的行將會聚集在一起。

0

您可以爲每個部分創建多個查詢或多次循環數據並根據使用php的描述類型進行過濾。

$descriptions = array('Content needs updating','Difficulty in navigating/finding content'); 
$rows = <fetch all rows from the query>; 
foreach($descriptions as $description) 
{ 
    echo '<h1>',$description,'</h1>'; 
    foreach($rows as $row) 
    { 
     if ($row['description'] == $description) 
     { 
      echo $row['text'],'<br />'; 
     } 
    } 
}