【问题标题】:How remove duplicate value in PHP [duplicate]如何删除 PHP 中的重复值 [重复]
【发布时间】:2018-08-30 14:46:03
【问题描述】:

我有一些数据存储在 $cache[] 中,其中有一些数字。如何删除打印输出中的重复值? :

<?

#mysql connect
mysql_connect($host,$user,$pass) or die(mysql_error());
mysql_select_db($name) or die(mysql_error());

function get_numerics ($str) {
    preg_match_all('/\d+/', $str, $matches);
    return $matches[0];
}


function validatecard($number) {
//preg_match_all('/^[6-9][0-9]{9}$/', $number, $found);
preg_match_all('/^[0-9]{4}$/',$number, $found);

//print_r($found);
return $found[0];

 }


$query = mysql_query("SELECT * FROM client WHERE status = 1 ORDER BY id") 
         or die(mysql_error());

while ($raw = mysql_fetch_array($query)) 

{

$name = $raw["postdata"];
$id = $raw["id"];
$cache = [];


  for($i=0;$i<=count(get_numerics($name));$i++){
    $ccv = get_numerics($name);
    $num = $ccv[$i];
    if (is_numeric($num)) {
    $cc = validatecard($num);
    if (!in_array($cc, $cache)){
        $cache[] = $cc;
}   
}
}



print_r($cache);

}

?>

我使用了一些函数,例如 :array unique 并将其转换为 json 或序列化...但不起作用。

【问题讨论】:

  • array_unique(array_values($cache));
  • 我尝试将其应用于我的代码不起作用

标签: php mysql


【解决方案1】:

使用array_unique($array) 函数。

它删除数组的重复值。

请查看此以获取更多信息:

http://php.net/manual/en/function.array-unique.php

【讨论】:

  • 以下代码对我不起作用
【解决方案2】:

如果 $cache 是多维的,那么 array_unique 将不起作用。 您可能想使用:

$input = array_map("unserialize", array_unique(array_map("serialize", $input)));

见:How to remove duplicate values from a multi-dimensional array in PHP

【讨论】:

  • 我试图将它应用到我的代码不起作用
【解决方案3】:

或者让数据库用 DISTINCT 处理删除重复项

SELECT 
  DISTINCT
     id 
   , postdata
FROM 
 client 
WHERE 
 status = 1 
ORDER BY
 id ASC

【讨论】:

  • postdata 列内容混合数据不仅是数值
  • 所以? DISTINCT 不仅适用于数字,还适用于混合数据
  • postdata 列内容例如:id 1 postdata : xxx 123 | id 2 后数据:你好 123 | id 3 postdata : 嘿 123 | id 4 后数据:xxx 000 |我只需要 2 行 123 和 000 没有重复
猜你喜欢
  • 2013-04-10
  • 1970-01-01
  • 2021-04-02
  • 2017-06-01
  • 2019-12-08
  • 1970-01-01
  • 1970-01-01
  • 2015-09-24
相关资源
最近更新 更多