0

all I want to remove the duplicate value from this Array

Array ( [0] => Array ( [0] => Ajay Patel [1] => Tag 1 ) [1] => Array ( [0] => Tag 1 [1] => Tag 3 ) [2] => Array ( ) [3] => Array ( ) [4] => Array ( ) ) 

I tried this solution from How to remove duplicate values from a multi-dimensional array in PHP

$result2 = array_map("unserialize", array_unique(array_map("serialize", $result2)));

But i think something is wrong here, i am getting this as result.

Array ( [0] => Array ( [0] => Ajay Patel [1] => Tag 1 ) [1] => Array ( [0] => Tag 1 [1] => Tag 3 ) [2] => Array ( ) ) 

What i want is

Array ( [0] => Ajay Patel [1] => Tag 1 [2] => Tag 3 ) 

Tag 1 is removed because its 2 times...

9
  • 1
    @silly can't you see the "Tag 1" two times, please understand the question first. Commented Feb 23, 2012 at 8:08
  • please post the results-that you expect Commented Feb 23, 2012 at 8:10
  • 1
    Ajay, that is an array of arrays. the arrays present in the main array are unique to each other, even if they hold some common values. Commented Feb 23, 2012 at 8:10
  • @AndreiG, in that link i have posted in question have the same situation. so what is another way to solve it ? Commented Feb 23, 2012 at 8:12
  • 1
    Ajay, please post the exact result you are expecting in the question (marked as code) so that we can see what you want to achieve Commented Feb 23, 2012 at 8:21

3 Answers 3

2
$result2 = array_unique(call_user_func_array('array_merge',$result2)); 

In modern PHP, the same technique can be written as:

$result2 = array_unique(array_merge(...$result2)); 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! it works for me but logically i am not getting clear how it works.BTW Thanks
The inner part (i.e. call_user_func_array('array_merge', $result2)) merges the sub-arrays into one flat array. The outer array_unique() call removes the duplicate values. This is a nice solution for two-dimensional arrays but will not scale for n-dimensional arrays. Which your question originally referred to. So I'm not quite sure if this really solves your problem or if your question's title is wrong.
2

try this

$result = array(); function merge_values(array &$array, $mixed) { if(is_array($mixed)) { foreach($mixed as $tags) { merge_values($array, $tags); } } else { if(null !== $mixed && strlen($mixed) > 0 && false === array_search($mixed, $array)) { $array[] = $mixed; } } } merge_values($result, $array); print_r($result); 

Comments

0

I think you should try this

function uniqueElements($outerArray){ $result=array(); foreach ($outerArray as $innerArray){ $result=array_merge($innerArray); } return array_unique($result); } 

1 Comment

Please prove that this answer works as required by providing a 3v4l.org link. That array_merge() looks dead wrong to me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.