0

contains the following i am trying get array_unique value from multidimensional associative array

Here, i am only showing only sample array which is similar to this.

$array =  ['games'=>[['vollyball', 'football'], ['vollyball', 'football'], ['rubby', 'chess']]];

Here is tried so for

foreach ($array as $key => &$value) {
    $value = array_unique($value);
}

echo "<pre>";
print_r($array);
echo "</pre>";
exit;

Here i am expecting output is,

 $array =  ['games'=>[['vollyball', 'football'], ['rubby', 'chess']]];

Here the array should be same even after removing duplicate from multidimensional array.

Thanks for your time and suggestions.

1 Answers1

1

you could try the following:

$a=array_values(array_unique(array_merge(...$array['games'])));

This assumes that all your usable values are below $array['games'].

Edit:

Here is another way, using array_walk:

array_walk($array['games'],function($itm){global $res; $res[json_encode($itm)]=$itm;});

echo json_encode(array_values($res));

I don't like the global $res array very much, but this is a way forward, I believe. In the callback function of array_walk() I add all values to an associative array ($res). The keys are JSON representations of their actual values. This way I will overwrite identical values in the associative array $res and will end up with a set of unique values when I apply the array_values() function at the end to turn it back into a non-associative array.

The result is:

[["vollyball","football"],["rubby","chess"]]

Here is a little demo you can check out: http://rextester.com/JEKE60636

2. edit

Using a wrapper function I can now do without the global variable $res and do the operation in-place, i. e. removing duplicate elements directly from the source array:

function unique(&$ag){
 array_walk($ag,function($itm,$key) use (&$ag,&$res) {
     if (isset($res[json_encode($itm)]))  array_splice($ag,$key,1);
     else                                 $res[json_encode($itm)]=1.;
 });
}

unique($array['games']);

echo json_encode($array)

This will result in

{"games":[["vollyball","football"],["rubby","chess"]]}

see here: http://rextester.com/YZLEK39965

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43