PHP: check for duplicate values ​​in a multidimensional array

I have a problem with multidimensional arrays.

Given the following multidimensional array:

Array( [0] => Array("a", "b", "c") [1] => Array("x", "y", "z") [2] => Array("a", "b", "c") [3] => Array("a", "b", "c") [4] => Array("a", "x", "z") ) 

I want to check its values ​​and find duplicates (i.e. keys 0, 2 and 3), leaving only one pair of keywords, deleting the rest, which will lead to something like this:

 Array( [0] => Array("a", "b", "c") [1] => Array("x", "y", "z") [2] => Array("a", "x", "z") ) 

How can i do this?

+4
source share
6 answers

This will remove duplicate elements from the array using array_unique() :

 $new_arr = array_unique($arr, SORT_REGULAR); 
+11
source
+2
source

You can simply do this using in_array ()

 $data = Array( 0 => Array("a", "b", "c"), 1 => Array("x", "y", "z"), 2 => Array("a", "b", "c"), 3 => Array("a", "b", "c"), 4 => Array("a", "x", "z"), ); $final = array(); foreach ($data as $array) { if(!in_array($array, $final)){ $final[] = $array; } } 

which will give you something like

 array(3) { [0] => array(3) { [0] => string(1) "a" [1] => string(1) "b" [2] => string(1) "c" } [1] => array(3) { [0] => string(1) "x" [1] => string(1) "y" [2] => string(1) "z" } [2] => array(3) { [0] => string(1) "a" [1] => string(1) "x" [2] => string(1) "z" } } 
+2
source

With serialization, you can use serialization to compare arrays.

 var_dump(makeUnique($data)); function makeUnique(array $data) { $serialized = array_map(create_function('$a', 'return serialize($a);'), $data); $unique = array_unique($serialized); return array_intersect_key($unique, $data); } 

Good luck

+1
source
 $arr = ...; $final = array(); sort($arr); foreach ($arr as $el) { if (!isset($prev) || $el !== $prev) $final[] = $el $prev = $el; } 

This is a more efficient solution 1 (log n + n instead of quadratic), but it relies on the full order between all elements of the array that you may not have (for example, if the internal arrays have objects).

1 More efficient than using in_array . It turns out that array_unique really uses this algorithm, so it has the same disadvantages.

0
source

To test the use of array_unique on multidimensional arrays, you need to flatten it like this using implode.

  $c=count($array) for($i=0;$i<$c;$i++) { $flattened=implode("~",$array[$i]); $newarray[$i]=$flattened; } if(count(array_unique($newarray) <count($newarray)) { //returns true if $array contains duplicates //can also use array_unique on $newarray //to remove duplicates, then explode, //to return to default state } 

Hope this is helpful, it took some time to get it.

0
source

Source: https://habr.com/ru/post/1339073/


All Articles