In this tutorial I will show you how to remove duplicates from multidimensional array in PHP. array_unique() function works on single dimensional array not on multidimensional arrays. After googling I have found a way to get unique multidimensional array using serialization of array. Serialization is used to storing or passing PHP values around without losing their type and structure.
Steps to remove duplicates from multidimensional array
1. We will use serialize () function to serialize the array. Then use map php inbuilt function.
$serialize_array = array_map("serialize", $multi_array_data);
2. Then we will use array_unique to get remove duplicates from multidimensional array
$unique_serialize_array = array_unique($serialize_array);
3. Now use unserialize() function to make the serialized string into a PHP value.
$final_array = array_map("unserialize", $unique_serialize_array);
Function to remove duplicates from multidimensional array
function multi_array_unique($array_data){ $array_data = array_map("unserialize", array_unique(array_map("serialize", $array_data))); return $array_data; }
Example 1
$multi_array = array( array( "name" => "rahul" ), array( "name" => "rahul" ), array( "name" => "rajesh" ) ); echo ' <pre>'; print_r($multi_array); echo '</pre> '; $unique_array = multi_array_unique($multi_array); echo ' <pre>'; print_r($unique_array); echo '</pre> ';
Output
Array ( [0] => Array ( [name] => rahul ) [2] => Array ( [name] => rajesh ) )
Example 2
$multi_array = array( array( "name" => "rahul", "age" => "25" ), array( "name" => "rahul", "age" => "25" ), array( "name" => "rajesh", "age" => "32" ) ); echo ' <pre>'; print_r($multi_array); echo '</pre> '; $unique_array = multi_array_unique($multi_array); echo ' <pre>'; print_r($unique_array); echo '</pre> ';
Output
Array ( [0] => Array ( [name] => rahul [age] => 25 ) [2] => Array ( [name] => rajesh [age] => 32 ) )