Home >Backend Development >PHP Tutorial >PHP two-dimensional array deduplication example analysis
This article analyzes the method of deduplication of two-dimensional arrays in PHP through examples. Share it with everyone for your reference, the details are as follows:
Everyone knows that one-dimensional arrays can reuse the system function array_unique($arr)
And today I used a two-dimensional array, and I also want to reuse it. Baidu has a lot of them. Convert 2D to 1D and then use array_unique($arr)
I was very annoyed by it, so I decided to write one myself. Simpler and easier to understand than his, record it for later use
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 'id: '.$v['id'].'psid: '.$v['psid'].' fullname: '.$v['fullname'].' userid: '.$v['userid'].'<br/>'; } //二维数组简单去重 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; }
Print result:
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
Note: in_array($need,$arr,$strict)
in this method Prior to PHP version 4.2.0, $need was not allowed to be an array. If $stric is true, it will strictly match the types to be found in $need and $arr