且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在关联数组中查找重复值,并将其添加到计数中

更新时间:2023-12-02 23:23:22

如果要检测正在创建的数组中的重复项,则可以避免多次遍历该数组:

If you want to detect dups in an array that you are creating, something like this avoid having to go through the array multiple times:

$arr=array();
while($row = mysql_fetch_array($result))  {                  
  $arr[$row['prodTitle']] = isset($arr[$row['prodTitle']]) 
                               ? $arr[$row['prodTitle']] +1 
                               : 0;                    
}
$dups = array_keys(array_filter($arr)); //any key => 0 will be filtred out

如果您只想通过SQL直接获取dups,请查看以下内容:

If you want to just get the dups directly by SQL, have a look at this:

您当前的查询-

SELECT prodTitle 
  FROM product 
WHERE prodTitle != '{$keyword}' 
  AND creditCard IN( SELECT creditCard FROM product WHERE prodTitle ='{$keyword}');

给出了这样的数据

prod cc
A    1
A    2
A    3
A    1
A    1
B    15
B    1
B    2
B    21
C    10
C    1

返回此集合(带有$ keyword =='A'):

returns this set (with $keyword=='A'):

prod 
B
B
C

仅返回 记录的汇总查询,其中在非X上使用的信用卡也至少在X上使用过两次-

An aggregate query that returns only records where credit cards used on non-X were also used on X at least twice --

SELECT p1.prodTitle, COUNT(p2.creditCard) AS numrecords
  FROM product p1
    JOIN product p2
    ON (p1.creditCard = p2.creditCard)
WHERE p1.prodTitle != '{$keyword}'
  AND p2.prodTitle = '{$keyword}'
GROUP BY p1.prodTitle 
  HAVING COUNT(p2.creditCard) > 1;

给定相同的数据,返回此集合:

given the same data, returns this set:

prod  num
B    2

执行聚合查询可以避免所有关于循环的混乱.这是链接到MySQL聚合列表功能.

Doing an aggregate query avoids all the messing about with loops. Here's a link to the MySQL list of aggregate functions.