Group By将第一列拆分两次

时间:2017-01-28 17:06:17

标签: php mysql foreach group-by

+----+---------+---------+---------+
| id | column1 | column2 | column3 |
+----+---------+---------+---------+
|  1 | Main1   | Sub1    | Sub1_6  |
|  2 | Main2   | Sub1    | Sub1_5  |
|  3 | Main3   | Sub5    | Sub5_1  |
|  4 | Main1   | Sub2    | Sub2_6  |
|  5 | Main2   | Sub1    | Sub1_3  |
|  6 | Main2   | Sub1    | Sub1_1  |
|  7 | Main1   | Sub1    | Sub1_3  |
+----+---------+---------+---------+

在这种情况下,我希望显示类似的内容;

  • Main1 - (3)
    • Sub1 - (2)
      • Sub1_6 - (1)
      • Sub1_3 - (1)
    • Sub2 - (1)
      • Sub2_6 - (1)
  • Main2 - (3)
    • Sub1 - (3)
      • Sub1_5 - (1)
      • Sub1_3 - (1)
      • Sub1_1 - (1)
  • Main3 - (1)
    • Sub5 - (1)
      • Sub5_1 - (1)

我尝试过以下代码,但它会分割所有代码。

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

$con = mysqli_connect($servername, $username, $password, $dbname);

$sql = mysqli_query($con, 'SELECT column1,column2,column3,COUNT(*) FROM table GROUP BY column1,column2,column3');
foreach($sql as $row) {
    echo "<ul>";
    echo "<li>" . $row['column1'] . " - (" . $row['COUNT(*)'] . ")</li>";
    echo "<ul>";
    echo "<li>" . $row['column2'] . " - (" . $row['COUNT(*)'] . ")</li>";
    echo "<ul>";
    echo "<li>" . $row['column3'] . " - (" . $row['COUNT(*)'] . ")</li>";
    echo "</ul>";
    echo "</ul>";
    echo "</ul>";
}

这些代码看起来像这样,所以问题是;在这种情况下,它将Main1拆分两次,我想将它们分组并显示为子。

  • Main1 - (2)
    • Sub1 - (2)
      • Sub1_6 - (1)
      • Sub1_3 - (1)
  • Main1 - (1)
    • Sub2 - (1)
      • Sub2_6 - (1)
  • Main2 - (3)
    • Sub1 - (3)
      • Sub1_5 - (1)
      • Sub1_3 - (1)
      • Sub1_1 - (1)
  • Main3 - (1)
    • Sub5 - (1)
      • Sub5_1 - (1)

它可能有超过2个潜艇,所以我需要一些动态的东西。

0 个答案:

没有答案