我想以特定的结构化方式显示一些MySQL数据。 比方说,我在MySQL数据库中有这个数据
id sections items
1 Section A Item 1
1 Section A Item 2
1 Section A Item 3
1 Section A Item 4
1 Section B Item 5
1 Section B Item 6
1 Section C Item 7
1 Section C Item 8
1 Section A Item 9
1 Section D Item 10
1 Section D Item 11
如何让它在PHP中显示如下:
SECTION A
---------
Item 1
Item 2
Item 3
Item 4
Item 9
SECTION B
---------
Item 5
Item 6
SECTION C
---------
Item 7
Item 8
SECTION D
---------
Item 10
Item 11
答案 0 :(得分:2)
$sql = mysql_query("SELECT sections, items
FROM my_table
ORDER BY sections");
$lastSection = '';
while($row = mysql_fetch_array($sql)) {
if($lastSection != $row['sections'])
echo $row['sections'] . '<br />';
echo $row['items'] . '<br />';
$lastSection = $row['sections'];
}
答案 1 :(得分:0)
尝试从“section”获取来自DB的所有数据,并从plain array中显示它。
<? $currentSection = null; ?>
<? foreach ($data as $row): ?>
<? if ($row['section'] != $currentSection): ?>
<? $currentSection = $row['section']; ?>
<h1><?=$row['section']?></h1>
<? endif; ?>
<div><?=$row['item']?></div>
<? endforeach; ?>