phparraysmultidimensional-arrayarray-filterarray-unique

Remove Duplicate Nested Arrays From Multidimenssional Array By Nested Array Key


I am trying to create an array where I need to filter with a certain key (fileid) so that it returns only unique keys for parent array. Here is what I have..

Array
(
    [ABCD] => Array
        (
            [0] => Array
                (
                    [fileid] => 5454554
                    [filename] => myfile1.txt
                )

            [1] => Array
                (
                    [fileid] => 5454954
                    [filename] => myfile2.txt
                )

            [2] => Array
                (
                    [fileid] => 5454554
                    [filename] => myfile1.txt
                )

        )

    [EFGH] => Array
        (
            [0] => Array
                (
                    [fileid] => 5429654
                    [filename] => myfile2.txt
                )

            [1] => Array
                (
                    [fileid] => 5433954
                    [filename] => myfile2.txt
                )

            [2] => Array
                (
                    [fileid] => 5429654
                    [filename] => myfile1.txt
                )

        )

)

The first keys (ABCD and EFGH) are File Owner IDs. The nested arrays contains the File ID and the FIle Name. I need to filter it so that every duplicate nested array (having same fileid) is removed.

I tried this this and this and many other solutions found on the web. But no luck. I also tried

$result =  array_map("unserialize", array_unique(array_map("serialize", $file_array)));  

No Luck again. Can someone please guide me to the right direction?

Thanks in advance.


Solution

  • You can use a combination of array_map and array_filter like so:

    array_map(
        function($arr) {
            $exists = [];
            return array_values(
                array_filter(
                    $arr,
                    function($arr1) use (&$exists) {
                        if (isset($exists[$arr1['fileid']])) {
                            return false;
                        }
                        $exists[$arr1['fileid']] = true;
                        return true;
                    }
                )
            );
        },
        $file_array,
    );
    

    Note: I used array_values to ensure the resultant array has consecutive numerical keys. If you want to keep the original numerical keys then it can be omitted.