【问题标题】:Display MySQL Data in PHP in a Particular Structured Manner [duplicate]以特定的结构化方式在 PHP 中显示 MySQL 数据
【发布时间】:2012-10-28 16:59:19
【问题描述】:

可能重复:
Displaying a table in PHP with repeated columns

我想以特定的结构化方式显示一些 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

【问题讨论】:

  • 在 mysql 查询中使用 where 子句,例如 SELECT items FROM table_name WHERE setions='Section A'
  • 您希望所有这些都在同一个查询中还是在单独的查询中?

标签: php mysql


【解决方案1】:
$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'];
}

【讨论】:

    【解决方案2】:

    尝试从按“部分”排序的数据库中获取所有数据并从普通数组中显示。

    <? $currentSection = null; ?>
    <? foreach ($data as $row): ?>
      <? if ($row['section'] != $currentSection): ?>
        <? $currentSection = $row['section']; ?>
        <h1><?=$row['section']?></h1>
      <? endif; ?>
      <div><?=$row['item']?></div>
    <? endforeach; ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-10
      • 1970-01-01
      • 1970-01-01
      • 2016-02-11
      • 1970-01-01
      • 2017-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多