如何在foreach循环中将mySQL数据库中的类似结果分组?

时间:2017-06-06 12:30:32

标签: php mysql loops pdo

$pdo = $db->prepare('SELECT * FROM animals WHERE id = :id ');  
$pdo->execute(array('id' => $id));
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
     $name = $row["name"];
     echo $name."<br>";
}

我的循环结果现在 -

cat
cat
cat
cat
dog
bird

我希望将结果分组,如果它们相似,那么我得到这样的结果 -

cat
dog
bird

4 个答案:

答案 0 :(得分:5)

不同的方式: -

1 DISTINCT: -

$pdo = $db->prepare('SELECT DISTINCT name FROM animals WHERE id = :id ');

2 GROUP BY: -

$pdo = $db->prepare('SELECT name FROM animals WHERE id = :id  GROUP BY name');

答案 1 :(得分:4)

您可以使用 GROUP BY

示例

 $pdo = $db->prepare('SELECT * FROM animals WHERE id = :id  GROUP BY name'); 

或者您可以使用 DISTINCT

示例 -

$pdo = $db->prepare('SELECT DISTINCT name FROM animals WHERE id = :id'); 

答案 2 :(得分:4)

Sql DISTINCT条款是你的朋友。 或者,通过php进行这样做,

$pdo = $db->prepare('SELECT * FROM animals WHERE category = :category ');  
        $pdo->execute(array('category' => $category));
        while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
            $name[$row["name"]] = $row["name"];
            echo $name."<br>";
        }

答案 3 :(得分:1)

使用mysql的DISTINCT来获取表格中的唯一记录

$pdo = $db->prepare('SELECT DISTINCT name FROM animals WHERE id = :id ');