3

Got a multidimensional array like this one:

$A = array(
  [0]=>
  array(
    ["rel"]=> 4
    ["name"]=> "Bar"
    ...
  )
  [1]=>
  array(
    ["rel"]=> 2
    ["name"]=> "Bar"
    ...
  )
  [2]=>
  array(
    ["rel"]=> 1
    ["name"]=> "Foo"
    ...
  )
  [3]=>
  array(
    ["rel"]=> 5
    ["name"]=> "Bar"
    ...
  )
  [4]=>
  array(
    ["rel"]=> 4
    ["name"]=> "Tee"
    ...
  )
)

I want to remove duplicates based on a specific key while maintaining the original array structure except index keys.

For the sake of this example let's say I want to remove those sub-arrays with identical key ["name"].

So the final result should look like this:

$X = array(
  [0]=>
  array(
    ["rel"]=> 4
    ["name"]=> "Bar"
    ...
  )
  [1]=>
  array(
    ["rel"]=> 1
    ["name"]=> "Foo"
    ...
  )
  [2]=>
  array(
    ["rel"]=> 4
    ["name"]=> "Tee"
    ...
  )
)

I'm looking for an efficient solution to this problem.

Ideally an array_unique function that accepts a key value as a parameter to find repetitions on a given array.

$X = array_key_unique($A, 'name');

Oriol
  • 11,660
  • 5
  • 35
  • 37
  • possible duplicate of [How to remove duplicate values from a multi-dimensional array in PHP](http://stackoverflow.com/questions/307674/how-to-remove-duplicate-values-from-a-multi-dimensional-array-in-php) – castis Feb 18 '15 at 23:41
  • I don't believe this solutions lets me target specific key(s). See how the $X array doesn't include element 1 and 3 of $A despite having different `rel` values. – Oriol Feb 18 '15 at 23:58

2 Answers2

6

This function should do the job:

function array_key_unique($arr, $key) {
    $uniquekeys = array();
    $output     = array();
    foreach ($arr as $item) {
        if (!in_array($item[$key], $uniquekeys)) {
            $uniquekeys[] = $item[$key];
            $output[]     = $item;
        }
    }
    return $output;
}

And applied to the particular problem mentioned above:

$X = array_key_unique($A, 'name');
Oriol
  • 11,660
  • 5
  • 35
  • 37
0

Try this..

 for ($i = 0; $i < count($A); $i++)
    {
      $repeated= null;
      for ($j = $i+1; $j < count($A); $j++)
      {
        if (strcmp($A[$j]['name'],$A[$i]['name']) === 0)
        {
          $repeated= $j;
          break;
        }
      }
      if (!is_null($repeated))
        array_splice($A,$repeated,1);
    }
    print_r($A);
Deenadhayalan Manoharan
  • 5,436
  • 14
  • 30
  • 50