php - Remove duplicate in array based on column value -


i need this. have following array:

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

i want remove duplicate rows comparing values of column 'a'. 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 simple way this?

you can create small array of possible values of field a using array_map(), grab unique values array_unique() , intersect 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'))); 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -