当前位置:Gxlcms > PHP教程 > PHP二维数组去重

PHP二维数组去重

时间:2021-07-01 10:21:17 帮助过:24人阅读

$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);
Array(    [0] => Array        (            [title] => 1111            [date] => 2222        )    [1] => Array        (            [title] => 4444            [date] => 3333        ))

$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);
Array(    [0] => Array        (            [title] => 1111            [date] => 2222        )    [1] => Array        (            [title] => 4444            [date] => 3333        ))


这个方法简单,但也有点缺陷,一是把原先索引弄没了,二是用额外变量存数组占用了更多内存,数组较大时会有些影响

人气教程排行