Oriol
Oriol

Reputation: 12670

Remove duplicates based on a specific key

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');

Upvotes: 3

Views: 1655

Answers (2)

Deenadhayalan Manoharan
Deenadhayalan Manoharan

Reputation: 5444

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);

Upvotes: 0

Oriol
Oriol

Reputation: 12670

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');

Upvotes: 6

Related Questions