PHP two-dimensional array deduplication example analysis

高洛峰
Release: 2023-03-03 13:42:01
Original
1280 people have browsed it

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 &#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

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
Copy after login

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


Related labels:
php
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template