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.
2
Answers
You can use a combination of
array_map
andarray_filter
like so: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.A simple couple of loops where you remember the fileid’s that you have seen in the inner array. If you see a fileid twice, you unset that occurance of the array.
Note using
&$owners
in the outer loop so you can actually remove an occurance from within the foreach loopRESULT
OR
Build a new array containing only the non duplicated files