Reputation: 61
I have a multi dimensional array and I need to cross check it for duplicate results and if they are duplicated remove the array with the duplicate results. I need to check 3 keys for duplication; number, departure and arrival. Here is an example array where the 3rd array is a duplicate and would need to be deleted:
[Cars] => Array
(
[0] => Array
(
[cartype] => car1
[number] => 123
[craft] => 456
[departure] => GHY
[departtime] => 20:25
[arrival] => PUI
[arrivetime] => 22:50
)
[1] => Array
(
[cartype] => car2
[number] => 567
[craft] => 890
[departure] => LHY
[departtime] => 16:25
[arrival] => PGY
[arrivetime] => 23:50
)
[2] => Array
(
[cartype] => car2
[number] => 567
[craft] => 890
[departure] => LHY
[departtime] => 16:25
[arrival] => PGY
[arrivetime] => 23:50
)
)
I would really appreciate some help.
Thanks,
Upvotes: 1
Views: 45
Reputation:
Try the following in order to completely remove identical duplicate sub-arrays.
$arr = [['cartype' => 'car1','number' => '123','departure' => 'GHY','arrival' => 'PUI'],
['cartype' => 'car2','number' => '567','departure' => 'LHY','arrival' => 'PGY'],
['cartype' => 'car2','number' => '567','departure' => 'LHY','arrival' => 'PGY']];
$out = [];
while (list($k, $v) = each($arr)) {
if(!in_array($v,$out)) {
array_push($out,$v);
}
}
print_r($out);
// output
Array
(
[0] => Array
(
[cartype] => car1
[number] => 123
[departure] => GHY
[arrival] => PUI
)
[1] => Array
(
[cartype] => car2
[number] => 567
[departure] => LHY
[arrival] => PGY
)
)
check the example here
EDIT In case you only want to use for checking duplicate results.
$arr = [['cartype' => 'car1','number' => '123','departure' => 'GHY','arrival' => 'PUI'],
['cartype' => 'car2','number' => '567','departure' => 'LHY','arrival' => 'PGY'],
['cartype' => 'car2','number' => '567','departure' => 'LHY','arrival' => 'PGY']];
$out = [];
$checks = [];
while (list($k, $v) = each($arr)) {
if(!in_array([$v['number'],$v['departure'],$v['arrival']],$checks)) {
array_push($checks,[$v['number'],$v['departure'],$v['arrival']]);
array_push($out,$v);
}
}
print_r($out);
// output
Array
(
[0] => Array
(
[cartype] => car1
[number] => 123
[departure] => GHY
[arrival] => PUI
)
[1] => Array
(
[cartype] => car2
[number] => 567
[departure] => LHY
[arrival] => PGY
)
)
check the new example here
Upvotes: 0
Reputation: 92854
The solution using in_array
function and custom $hash_map
container(each entry is comprised of number
, departure
and arrival
keys values):
// $arr is your initial array
// hash container
$hash_map = [];
foreach ($arr['Cars'] as $k => &$v) {
$hash = $v['number'] . $v['departure'] . $v['arrival'];
if (in_array($hash, $hash_map)) {
unset($arr['Cars'][$k]); // removing duplicate item
} else {
$hash_map[] = $hash;
}
}
unset($hash_map);
print_r($arr);
Upvotes: 1