Home > Backend Development > PHP Tutorial > PHP二维数组去重

PHP二维数组去重

WBOY
Release: 2016-06-23 13:17:46
Original
1195 people have browsed it

$array = array(
'1'=>array('title'=>'1111','date'=>'2222'),
'2'=>array('title'=>'1111','date'=>'5555'),
'3'=>array('title'=>'4444','date'=>'3333')
);  


想用写一个函数,传入数组, 删除含有重复的值,
 例  $array['2'] 的 'title' => '1111' 在 $array['1']中也有,删除$array['2'], $array['3']为$array['2']


回复讨论(解决方案)

$array = array('1'=>array('title'=>'1111','date'=>'2222'),'2'=>array('title'=>'1111','date'=>'5555'),'3'=>array('title'=>'4444','date'=>'3333'));$tmp = array();foreach($array as $v)  if(!isset($tmp[$v['title']])) $tmp[$v['title']] = $v;$array = array_values($tmp);print_r($array);
Copy after login
Copy after login
Array(    [0] => Array        (            [title] => 1111            [date] => 2222        )    [1] => Array        (            [title] => 4444            [date] => 3333        ))
Copy after login
Copy after login

$array = array('1'=>array('title'=>'1111','date'=>'2222'),'2'=>array('title'=>'1111','date'=>'5555'),'3'=>array('title'=>'4444','date'=>'3333'));$tmp = array();foreach($array as $v)  if(!isset($tmp[$v['title']])) $tmp[$v['title']] = $v;$array = array_values($tmp);print_r($array);
Copy after login
Copy after login
Array(    [0] => Array        (            [title] => 1111            [date] => 2222        )    [1] => Array        (            [title] => 4444            [date] => 3333        ))
Copy after login
Copy after login


这个方法简单,但也有点缺陷,一是把原先索引弄没了,二是用额外变量存数组占用了更多内存,数组较大时会有些影响
Related labels:
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