Home > Backend Development > PHP Tutorial > PHP二维数组去重实例分析

PHP二维数组去重实例分析

PHPz
Release: 2018-10-09 15:00:25
forward
929 people have browsed it

这篇文章主要介绍了PHP二维数组去重的方法,结合实例形式分析了php数组遍历、判断及去除重复项的相关操作技巧,需要的朋友可以参考下

本文实例分析了PHP二维数组去重的方法。分享给大家供大家参考,具体如下:

都知道一维数组去重用系统函数 array_unique($arr)

然后今天我用到二维数组了,也想去重,百度一大堆,都是将二维转一维 然后使用array_unique($arr)

看得我很恼火,所以决定自己写一个。比他的简单好懂,记录下来,以备后用

header('content-type:text/html;charset=utf8');
$arr = array(
array('id'=>1,'psid'=>'P101','fullname'=>'课程计划全称 101','userid'=>4),
array('id'=>1,'psid'=>'P101','fullname'=>'课程计划全称 101','userid'=>3),
array('id'=>1,'psid'=>'P101','fullname'=>'课程计划全称 101','userid'=>3),
array('id'=>1,'psid'=>'P101','fullname'=>'课程计划全称 101','userid'=>2),
array('id'=>2,'psid'=>'P102','fullname'=>'新课程计划','userid'=>4),
array('id'=>2,'psid'=>'P102','fullname'=>'新课程计划','userid'=>3),
array('id'=>2,'psid'=>'P102','fullname'=>'新课程计划','userid'=>3),
array('id'=>2,'psid'=>'P102','fullname'=>'新课程计划','userid'=>2)
);
$arr = er_array_unique($arr);
foreach($arr as $v){
  echo &#39;id: &#39;.$v[&#39;id&#39;].&#39;psid: &#39;.$v[&#39;psid&#39;].&#39; fullname: &#39;.$v[&#39;fullname&#39;].&#39; userid: &#39;.$v[&#39;userid&#39;].&#39;<br/>&#39;;
}
//二维数组简单去重
function er_array_unique($arr){
  $newarr = array();
  if(is_array($arr)){
    foreach($arr as $v){
      if(!in_array($v,$newarr,true)){
        $newarr[] = $v;
      }
    }
  }else{
     return false;
  }
  return $newarr;
}
Copy after login

打印结果:

id: 1psid: P101 fullname: 课程计划全称 101 userid: 4
id: 1psid: P101 fullname: 课程计划全称 101 userid: 3
id: 1psid: P101 fullname: 课程计划全称 101 userid: 2
id: 2psid: P102 fullname: 新课程计划 userid: 4
id: 2psid: P102 fullname: 新课程计划 userid: 3
id: 2psid: P102 fullname: 新课程计划 userid: 2
Copy after login

注意:此方法中的  in_array($need,$arr,$strict)

在 PHP 版本 4.2.0 之前,$need 不允许是一个数组。$stric 为 true 会严格去匹配 $need 和 $arr 中待查找的类型

更多相关教程请访问 php编程从入门到精通全套视频教程

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template