Heim  >  Artikel  >  Backend-Entwicklung  >  php去除数组中重复数据的二个例子

php去除数组中重复数据的二个例子

WBOY
WBOYOriginal
2016-07-25 08:55:37924Durchsuche
  1. /**

  2. * 去除数组中重复数据
  3. * by bbs.it-home.org
  4. **/
  5. $input = array("a" => "green","", "red","b" => "green", "","blue", "red","c" => "witer","hello","witer");
  6. //$result = array_unique($input); //去除重复元素
  7. $result = a_array_unique($input); //只留下单一元素
  8. foreach($result as $aa)
  9. {
  10. echo $aa."
    ";
  11. }
  12. function multi_unique($array) {
  13. foreach ($array as $k=>$na)
  14. $new[$k] = serialize($na);
  15. $uniq = array_unique($new);
  16. foreach($uniq as $k=>$ser)
  17. $new1[$k] = unserialize($ser);
  18. return ($new1);
  19. }
  20. function a_array_unique($array)//写的比较好

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

PHP自带的array_unique函数只适用于一维数组,对多维数组并不适用,这里实现一个php二维数组去重复的array_unique函数。

例子:

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

调用示例:

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


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