0

我有一个包含许多记录的表。我正在寻找一种有效的方法来计算元素重复的次数。

示例表:

id     name
1      ana
2      john
3      tom
4      ana 
5      john

到目前为止,我已经完成了,但效率低下。

$number  = 0;
for ($i =1 ; $i <= mysql_num_rows($query) ; $i++)
       for ($j = 1 ; $j <=mysql_num_rows($query); $j++)
           if ( $table[$i] == $table[$j])
                  $number++;
if ($number > 2 ) 
    echo $number;
4

5 回答 5

1

您可以直接在 SQL 中执行此操作

SELECT `name`, COUNT(*) AS `count`
FROM `table`
GROUP BY `name`

这会更有效率,因为您不必将每一行都传输到 PHP。

于 2012-04-04T16:03:12.300 回答
0
select count(1), name from table group by name;

count(1) name
2        ana
2        john
1        tom
于 2012-04-04T16:03:15.597 回答
0

你可以做到查询端

select count(id), name from table group by name
于 2012-04-04T16:04:22.003 回答
0

在这里,您可以获得最低的 id、名称以及它存在的次数:

select min(id),name,count(*) as cnt from table group by name

在一个 php 数组中:

$newarray= array_count_values ( $table );

http://php.net/manual/en/function.array-count-values.php

于 2012-04-04T16:07:29.693 回答
0
function check_number_of_times_elements_occur_in_array($a)//returns values of array as keys,associating values being their total occurences in the array
{
$r=array();
foreach($a as $v)
    ++$r[$v];
return $r;
}

根据您的需要访问返回的数组。

于 2012-04-07T10:51:09.000 回答