Array PHP two-dimensional array deduplication problem analysis

WBOY
Release: 2016-07-29 08:46:14
Original
954 people have browsed it

I wrote an article about array deduplication before, but it was limited to one-dimensional arrays. The following function can be used for two-dimensional arrays:

Copy the code The code is as follows:


//Remove duplicate values ​​from the two-dimensional array
function array_unique_fb($array2D)
{
foreach ($array2D as $v)
{
$v = join(",",$v); //For dimensionality reduction, you can also use implode to convert the one-dimensional array into a string connected with commas
$temp[] = $v;
}
$temp = array_unique($temp); //Remove repeated strings, that is, repeated one-dimensional arrays
foreach ($temp as $k => $v)
{
$temp[$k] = explode( ",",$v); //Reassemble the disassembled array
}
return $temp;
}


If you want to retain the key value of the array, you can use the following function:

Copy Code The code is as follows:


//Two-dimensional array removes duplicate values ​​and retains key values
function array_unique_fb($array2D)
{
foreach ($array2D as $k=>$v)
{
$v = join(",",$v); //For dimensionality reduction, you can also use implode to convert the one-dimensional array into a string connected with commas
$temp[$k] = $v;
}
$temp = array_unique ($temp); //Remove repeated strings, that is, repeated one-dimensional arrays
foreach ($temp as $k => $v)
{
$array=explode(",",$v); //Reassemble the disassembled array
$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;
}


That's it.
Two-dimensional array deduplication

Copy code The code is as follows:


$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);
?>

The above has introduced the analysis of array deduplication of two-dimensional arrays in PHP, including array aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

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