Skip to content
Advertisement

PHP array unique by column

How to filter an array to give unique elements according to one or more columns. Example:

array(
    array('name'=>'toto', 'type'=>'1', 'type2'=> '2')
    array('name'=>'tata', 'type'=>'1', 'type2'=> '3')
    array('name'=>'titi', 'type'=>'1', 'type2'=> '2')
    array('name'=>'tutu', 'type'=>'2', 'type2'=> '4')
    array('name'=>'tete', 'type'=>'3', 'type2'=> '2')
)

If we choose type and type2 as the unique column. The result of the algorithm should gives

array(
    array('name'=>'toto', 'type'=>'1', 'type2'=> '2')
    array('name'=>'tata', 'type'=>'1', 'type2'=> '3')
    array('name'=>'tutu', 'type'=>'2', 'type2'=> '4')
    array('name'=>'tete', 'type'=>'3', 'type2'=> '2')
)

I can think of an algorithm by hashing the type concatenate with type2, store in a table and using isset to find the existence. But I’m not sure that’s the best algorithm.

Advertisement

Answer

All you need is

$data = array(
    array('name'=>'toto', 'type'=>'1', 'type2'=> '2'),
    array('name'=>'tata', 'type'=>'1', 'type2'=> '3'),
    array('name'=>'titi', 'type'=>'1', 'type2'=> '2'),
    array('name'=>'tutu', 'type'=>'2', 'type2'=> '4'),
    array('name'=>'tete', 'type'=>'3', 'type2'=> '2')
);


$tmp = array();
foreach($data as $v) {
    $id = $v['type'] . "|" . $v['type2'];
    isset($tmp[$id]) or $tmp[$id] = $v;
}
print_r(array_values($tmp));
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement