$result = array( 0=>array('a'=>1,'b'=>'Hello'), 1=>array('a'=>1,'b'=>'other'), 2=>array('a'=>1,'b'=>'other'), );
If it is duplicated removed it, so the result is as follows:
$result = array( 0=>array('a'=>1,'b'=>'Hello'), 1=>array('a'=>1,'b'=>'other') );
Could any know to do this?
Thanks
The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed.
Approach: Declare an associative array containing key-value pair objects. Then use delete keyword to delete the array objects from an associative array.
No, you cannot have multiple of the same key in an associative array. You could, however, have unique keys each of whose corresponding values are arrays, and those arrays have multiple elements for each key. Save this answer.
Regardless what others are offering here, you are looking for a function called array_unique
Docs. The important thing here is to set the second parameter to SORT_REGULAR
and then the job is easy:
array_unique($result, SORT_REGULAR);
The meaning of the SORT_REGULAR
flag is:
compare items normally (don't change types)
And that is what you want. You want to compare arraysDocs here and do not change their type to string (which would have been the default if the parameter is not set).
array_unique
does a strict comparison (===
in PHP), for arrays this means:
$a === $b
TRUE
if $a and $b have the same key/value pairs in the same order and of the same types.
Output (Demo):
Array ( [0] => Array ( [a] => 1 [b] => Hello ) [1] => Array ( [a] => 1 [b] => other ) )
First things first, you can not use plain array_unique
for this problem because array_unique internally treats the array items as strings, which is why "Cannot convert Array to String" notices will appear when using array_unique for this.
So try this:
$result = array( 0=>array('a'=>1,'b'=>'Hello'), 1=>array('a'=>1,'b'=>'other'), 2=>array('a'=>1,'b'=>'other') ); $unique = array_map("unserialize", array_unique(array_map("serialize", $result))); print_r($unique);
Result:
Array ( [0] => Array ( [a] => 1 [b] => Hello ) [1] => Array ( [a] => 1 [b] => other ) )
Serialization is very handy for such problems.
If you feel that's too much magic for you, check out this blog post
function array_multi_unique($multiArray){ $uniqueArray = array(); foreach($multiArray as $subArray){ if(!in_array($subArray, $uniqueArray)){ $uniqueArray[] = $subArray; } } return $uniqueArray; } $unique = array_multi_unique($result); print_r($unique);
Ironically, in_array
is working for arrays, where array_unique
does not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With