0

我有一个类似于以下的表:

subcategory    category
------------------------
apples         fruits
oranges        fruits
pears          fruits
honda          cars
volvo          cars
audi           cars

使用 php 和 mySQL 打印出以下示例的简单方法是什么?

例子:

水果:

  • 苹果
  • 橘子

汽车:

  • 本田
  • 沃尔沃
  • 奥迪

我一直在努力解决这个问题几个小时,我很感激任何建议。

4

2 回答 2

0

Get a list of categories, and then subcategories in each categories.

<?php

$categories = array();

foreach ($results as $result) {
    $category = $result['category'];
    $categories[$category][] = $result['subcategory'];
}

This will then give you a multidimensional array, with categories and the keys, and the sub-categories as the values. You can loop over them as thus:

<ul>
<?php foreach ($categories as $category => $subcategories): ?>
  <li>
    <?php echo $category; ?>
    <ul>
<?php foreach ($subcategories as $subcategory): ?>
      <li><?php echo $subcategory; ?></li>
<?php endforeach; ?>
    </ul>
  </li>
<?php endforeach; ?>
</ul>
于 2012-07-29T19:53:16.720 回答
-1
$data = getData();
$dataByCat = array();
foreach($data as $row) {
   $dataByCat[$row['category']][] = $row;
}

$dataByCat will be an array in the "shape" of your bullet points.

于 2012-07-29T19:51:27.230 回答