I want to get a solution in PHP to get unique array based on sub array bases. Like this
Array
(
[0] => Array
(
[0] => 1227
[1] => 146
[2] => 1
[3] => 39
)
[1] => Array
(
[0] => 1227
[1] => 146
[2] => 1
[3] => 39
)
[2] => Array
(
[0] => 1228
[1] => 146
[2] => 1
[3] => 39
)
)
to
Array
(
[0] => Array
(
[0] => 1227
[1] => 146
[2] => 1
[3] => 39
)
[1] => Array
(
[0] => 1228
[1] => 146
[2] => 1
[3] => 39
)
)
I mean to say array[1]
should be removed as array[0]
and array[1]
are the same. I tried to use array_unique
but it didn't work for me.
A user-defined function can help in getting unique values from multidimensional arrays without considering the keys. You can use the PHP array unique function along with the other array functions to get unique values from a multidimensional array while preserving the keys.
To merge the duplicate value in a multidimensional array in PHP, first, create an empty array that will contain the final result. Then we iterate through each element in the array and check for its duplicity by comparing it with other elements.
You can use the PHP array_unique() function and PHP array_merge() function together to merge two arrays into one array without duplicate values in PHP.
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. Note: The returned array will keep the first array item's key type.
This can be done with array_unique
but you'll also need to use the SORT_REGULAR
(PHP 5.2.9+) flag:
$array = array(
array(1227, 146, 1, 39),
array(1227, 146, 1, 39),
array(1228, 146, 1, 39),
);
$array = array_unique($array, SORT_REGULAR);
Output:
Array
(
[0] => Array
(
[0] => 1227
[1] => 146
[2] => 1
[3] => 39
)
[2] => Array
(
[0] => 1228
[1] => 146
[2] => 1
[3] => 39
)
)
Demo!
For older versions of PHP, you could use the solution I linked to in the question's comments:
$array = array_map("unserialize", array_unique(array_map("serialize", $array)));
Hope this helps!
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