Remove duplicates based on a specific key

痞子三分冷 提交于 2019-12-07 14:40:58

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/28596110/remove-duplicates-based-on-a-specific-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!