-2

I need some help with this. I have the following array:

$result = array(
    0 => array('a'=>1,'b'=>'data1'),
    1 => array('a'=>2,'b'=>'data2'),
    2 => array('a'=>1,'b'=>'data3'),
);

I want to remove duplicate rows by comparing the values of column 'a'. The expected output should be:

array(
    0 => array('a'=>1,'b'=>'data1'),
    1 => array('a'=>2,'b'=>'data2'),
);

Or:

array(
    1 => array('a'=>2,'b'=>'data2'),
    2 => array('a'=>1,'b'=>'data3'),
);

Is there a simple way to do this?

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • Newer canonical with a battery of effective techniques: [Filter/Remove rows where column value is found more than once in a multidimensional array](https://stackoverflow.com/q/45603614/2943403) – mickmackusa May 20 '22 at 03:17

1 Answers1

13

You can create a small array of all possible values of field a using array_map(), grab all unique values from it with array_unique() and then intersect it with the original array using array_intersect_key().

$output = array_intersect_key(
    $result, 
    array_unique(array_map(function($item) {
        return $item['a'];
    }, $result))
);

Or, since 5.5:

$output = array_intersect_key($result, array_unique(array_column($result, 'a')));
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309