Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php get unique sub array [duplicate]

Tags:

arrays

php

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.

like image 471
Amit Kumar Sharma Avatar asked Sep 28 '13 16:09

Amit Kumar Sharma


People also ask

How do you get unique values in a multidimensional array?

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.

How can we get duplicate values in multidimensional array in PHP?

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.

How can I get unique values from two arrays in PHP?

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.

What is use of Array_unique 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.


1 Answers

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!

like image 146
Amal Murali Avatar answered Sep 21 '22 01:09

Amal Murali