Heim  >  Artikel  >  Backend-Entwicklung  >  php判断与去除数组中重复数据的方法

php判断与去除数组中重复数据的方法

WBOY
WBOYOriginal
2016-07-25 08:58:581000Durchsuche
  1. if (count($array) != count(array_unique($array))) {
  2. echo '该数组有重复值';
  3. }
  4. ?>
复制代码

PHP去除重复的数组数据

  1. $input = array("a" => "green","", "red","b" => "green", "","blue", "red","c" => "witer","hello","witer");

  2. //$result = array_unique($input); //去除重复元素
  3. $result = a_array_unique($input); //只留下单一元素
  4. foreach($result as $aa)
  5. {
  6. echo $aa."
    ";
  7. }
  8. function multi_unique($array) {
  9. foreach ($array as $k=>$na)
  10. $new[$k] = serialize($na);
  11. $uniq = array_unique($new);
  12. foreach($uniq as $k=>$ser)
  13. $new1[$k] = unserialize($ser);
  14. return ($new1);
  15. }
  16. function a_array_unique($array)//写的比较好

  17. {
  18. $out = array();
  19. foreach ($array as $key=>$value) {
  20. if (!in_array($value, $out))
  21. {
  22. $out[$key] = $value;
  23. }
  24. }
  25. return $out;
  26. }
  27. ?>
复制代码

PHP数组去除重复项 有个内置函数array_unique (),但是php的 array_unique函数只适用于一维数组,对多维数组并不适用。 以下实现一个二维数组的array_unique函数:

  1. function unique_arr($array2D,$stkeep=false,$ndformat=true)
  2. {
  3. // 判断是否保留一级数组键 (一级数组键可以为非数字)
  4. if($stkeep) $stArr = array_keys($array2D);
  5. // 判断是否保留二级数组键 (所有二级数组键必须相同)
  6. if($ndformat) $ndArr = array_keys(end($array2D));
  7. //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
  8. foreach ($array2D as $v){
  9. $v = join(",",$v);
  10. $temp[] = $v;
  11. }
  12. //去掉重复的字符串,也就是重复的一维数组
  13. $temp = array_unique($temp);
  14. //再将拆开的数组重新组装
  15. foreach ($temp as $k => $v)
  16. {
  17. if($stkeep) $k = $stArr[$k];
  18. if($ndformat)
  19. {
  20. $tempArr = explode(",",$v);
  21. foreach($tempArr as $ndkey => $ndval) $output[$k][$ndArr[$ndkey]] = $ndval;
  22. }
  23. else $output[$k] = explode(",",$v);
  24. }
  25. return $output;
  26. }
  27. ?>
复制代码

测试用例:

  1. $array2D = array('first'=>array('title'=>'1111','date'=>'2222'),'second'=>array('title'=>'1111','date'=>'2222'),'third'=>array('title'=>'2222','date'=>'3333'));
  2. print_r($array2D);
  3. print_r(unique_arr($array2D,true));
  4. ?>
复制代码

php判断数组中是否存在相同的值array_unique 1 2 下一页 尾页



Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn