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

WBOY
Release: 2016-05-17 09:16:56
Original
1039 people have browsed it

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

复制代码 代码如下:

//二维数组去掉重复值
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;
}

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

//二维数组去掉重复值 并保留键值
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;
}

大概就这样啦。
二维数组去重
复制代码 代码如下:

$arr = array(
array('id' => 1,'name' => 'aaa'),
array('id' => 2,'name' => 'bbb'),
array('id' => 3,'name' => 'ccc'),
array('id' => 4,'name' => 'ddd'),
array('id' => 5,'name' => 'ccc'),
array('id' => 6,'name' => 'aaa'),
array('id' => 7,'name' => 'bbb'),
);
function assoc_unique(&$arr, $key)
{
$rAr=array();
for($i=0;$i{
if(!isset($rAr[$arr[$i][$key]]))
{
$rAr[$arr[$i][$key]]=$arr[$i];
}
}
$arr=array_values($rAr);
}
assoc_unique(&$arr,'name');
print_r($arr);
?>
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