Home > php教程 > php手册 > PHP二维数组的去重问题解析

PHP二维数组的去重问题解析

PHPz
Release: 2018-10-09 15:12:24
forward
1316 people have browsed it

PHP数组去除重复项有个内置函数array_unique(),但是php的array_unique函数只适用于一维数组,对多维数组并不适用,以下提供一个二维数组的array_unique函数。

之前写了一篇关于数组去重的文章,但是仅限于一维数组。下面的函数可以用于二维数组:

代码如下:

//二维数组去掉重复值 
function array_unique_fb($array2D) 
{ 
foreach ($array2D as $v) 
{ 
$v = join(",",$v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串 
$temp[] = $v; 
} 
$temp = array_unique($temp); //去掉重复的字符串,也就是重复的一维数组 
foreach ($temp as $k => $v) 
{ 
$temp[$k] = explode(",",$v); //再将拆开的数组重新组装 
} 
return $temp; 
}
Copy after login

如果你想保留数组的键值,可以用下面的函数:

代码如下:

//二维数组去掉重复值 并保留键值 
function array_unique_fb($array2D) 
{ 
foreach ($array2D as $k=>$v) 
{ 
$v = join(",",$v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串 
$temp[$k] = $v; 
} 
$temp = array_unique($temp); //去掉重复的字符串,也就是重复的一维数组 
foreach ($temp as $k => $v) 
{ 
$array=explode(",",$v); //再将拆开的数组重新组装 
$temp2[$k]["id"] =$array[0]; 
$temp2[$k]["litpic"] =$array[1]; 
$temp2[$k]["title"] =$array[2]; 
$temp2[$k]["address"] =$array[3]; 
$temp2[$k]["starttime"] =$array[4]; 
$temp2[$k]["endtime"] =$array[5]; 
$temp2[$k]["classid"] =$array[6]; 
$temp2[$k]["ename"] =$array[7]; 
} 
return $temp2; 
}
Copy after login

大概就这样啦。
二维数组去重

代码如下:

<?php 
$arr = array( 
array(&#39;id&#39; => 1,&#39;name&#39; => &#39;aaa&#39;), 
array(&#39;id&#39; => 2,&#39;name&#39; => &#39;bbb&#39;), 
array(&#39;id&#39; => 3,&#39;name&#39; => &#39;ccc&#39;), 
array(&#39;id&#39; => 4,&#39;name&#39; => &#39;ddd&#39;), 
array(&#39;id&#39; => 5,&#39;name&#39; => &#39;ccc&#39;), 
array(&#39;id&#39; => 6,&#39;name&#39; => &#39;aaa&#39;), 
array(&#39;id&#39; => 7,&#39;name&#39; => &#39;bbb&#39;), 
); 
function assoc_unique(&$arr, $key) 
{ 
$rAr=array(); 
for($i=0;$i<count($arr);$i++) 
{ 
if(!isset($rAr[$arr[$i][$key]])) 
{ 
$rAr[$arr[$i][$key]]=$arr[$i]; 
} 
} 
$arr=array_values($rAr); 
} 
assoc_unique(&$arr,&#39;name&#39;); 
print_r($arr); 
?>
Copy after login

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

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