SoFunction
Updated on 2025-03-10

Analysis of the problem of deduplication in PHP two-dimensional array

I wrote an article about array deduplication before, but it is limited to one-dimensional arrays. The following functions can be used in two-dimensional arrays:
Copy the codeThe code is as follows:

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

If you want to keep the key values ​​of the array, you can use the following function:
Copy the codeThe code is as follows:

//Remove duplicate values ​​from the two-dimensional array and retain key values
function array_unique_fb($array2D)
{
foreach ($array2D as $k=>$v)
{
$v = join(",",$v); //Dimensional reduction, you can also use implode to convert a one-dimensional array into a string connected with a comma
$temp[$k] = $v;
}
$temp = array_unique($temp); //Remove duplicate strings, that is, duplicate 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;
}

It's probably that's it.
Two-dimensional array deduplication
Copy the codeThe code is as follows:

<?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<count($arr);$i++)
{
if(!isset($rAr[$arr[$i][$key]]))
{
$rAr[$arr[$i][$key]]=$arr[$i];
}
}
$arr=array_values($rAr);
}
assoc_unique(&$arr,'name');
print_r($arr);
?>