1

PHP二维数组去重

Posted by 晴云孤魂 on 2012 年 05 月 17 日 in Program Development, web development |

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;
}

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

 

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

二维数组去重

 

 
< ?php 
$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

Copyright © 2011-2021 晴云孤魂's Blog All rights reserved.
This site is using the Desk Mess Mirrored theme, v2.5, from BuyNowShop.com.

普人特福的博客cnzz&51la for wordpress,cnzz for wordpress,51la for wordpress