PHP如何在列中找到相同的值

时间:2019-02-22 04:08:47

标签: php html css mysql

嗨,我是php语言的新手,我需要在数据库表的Description列中找到相同的值。

id ------- DESCRIPTION

1 -------最终

2 -------考试

3 -------测试

4 -------测试

5 -------中

6 -------测验

7 -------测验

作为输出,它必须像:

最终

考试

测试

测试

测验

测验

如果一个值只是改变它们的样式就足够了,但是我真的不知道该怎么做。

<?php

$check = mysqli_query($connection,"SELECT * FROM EXAMS");
while($test=mysqli_fetch_array($check))
{

    echo $test["DESCRIPTION"];
}



?>

1 个答案:

答案 0 :(得分:1)

使用EXISTS子查询查找另一个id是否存在相同的值

$result = $connection->query("
    SELECT e.id, e.DESCRIPTION, EXISTS(
        SELECT *
        FROM EXAMS e2 
        WHERE e2.DESCRIPTION = e.DESCRIPTION
          AND e2.id <> e.id
    ) as is_duplicate
    FROM EXAMS e
    ORDER BY e.id
");

然后检查PHP是否重复(if ($row['is_duplicate'] == 1))并将其标记为粗体:

while($row = $result->fetch_assoc())
{
    if ($row['is_duplicate'] == 1) {
        echo "<strong>$row['DESCRIPTION']</strong><br>";
    } else {
        echo "$row['DESCRIPTION']<br>";
    }
}

PHP解决方案

$result = $connection->query("SELECT * FROM EXAMS");

$data = $result->fetch_all(MYSQLI_ASSOC);
$counts = array_count_values(array_column($data, 'DESCRIPTION'));

foreach($data as $row)
{
    if ($counts[$row['DESCRIPTION']] > 1) {
        echo "<strong>$row['DESCRIPTION']</strong><br>";
    } else {
        echo "$row['DESCRIPTION']<br>";
    }
}