PHP - MYSQL - 避免计算重复元素

时间:2016-04-20 19:02:55

标签: php mysql

我试图避免显示具有相同名称的元素。

例如我的表是:

+----------+----------------------+
|   name   |       category       |
+----------+----------------------+
|   AAA    |         Sport        |
+----------+----------------------+
|   BBB    |          City        |
+----------+----------------------+
|   CCC    |         Sport        |
+----------+----------------------+
|   DDD    |          Sun         |
+----------+----------------------+
|   EEE    |         Sport        |
+----------+----------------------+
|   FFF    |          Sun         |
+----------+----------------------+

如何获得一组category元素以避免重复?

输出数组:

["Sport", "City", "Sun"]

我的代码是:

<?php

      $return_arr = array();

      $sql="SELECT * FROM $DB_table";

      $resultCat = $conn->query($sql);     


      while($row = $resultCat->fetch_assoc()) {

           $category = $row['category'];
           $row_array['category'] = $row['category'];

           array_push($return_arr,$row_array);
           echo "<option value=$category>$category</option>";

     }
?>

3 个答案:

答案 0 :(得分:0)

尝试

SELECT DISTINCT category FROM #DB_Table

答案 1 :(得分:0)

尝试使用select distinct

 select distinct category from your_table;

答案 2 :(得分:0)

试试这个

select DISTINCT category from your_table group by category;