Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array unique by column

Tags:

php

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.

like image 781
Thanh Trung Avatar asked Oct 15 '25 03:10

Thanh Trung


1 Answers

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));
like image 56
Baba Avatar answered Oct 17 '25 16:10

Baba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!