Reputation: 59
I have multidimensional array like this.
array:8 [
0 => array:8 [
"SERIAL" => "qwerty"
"BRANCH" => "TEST1"
]
1 => array:8 [
"SERIAL" => "qwer"
"BRANCH" => "TEST1"
]
2 => array:8 [ // RETURN THIS AS ERROR AS THE BRANCH "TEST1" has already "qwerty" serial
"SERIAL" => "qwerty"
"BRANCH" => "TEST2"
]
3 => array:8 [
"SERIAL" => "qwerty"
"BRANCH" => "TEST1"
]
]
My goal is to return error if there is a duplicate value of "SERIAL" and different "BRANCH".
Any idea how to achieve this?
Upvotes: 1
Views: 69
Reputation: 7485
You could sort the array (here a copy) by SERIAL, and then if you have the same SERIAL values, check to see if they lie on different BRANCHs.
<?php
$dupes = false;
usort($result = $data, function($a, $b) use (&$dupes) {
$out = $a['SERIAL'] <=> $b['SERIAL'];
if($out === 0 && $a['BRANCH'] !== $b['BRANCH'])
$dupes = true;
return $out;
});
var_dump($dupes);
Output:
bool(true)
Upvotes: 1
Reputation: 23958
If you group the serials and branches then you can see if the unique count is more than one.
This will output all the duplicates not just the first.
foreach($arr as $sub){
$result[$sub['SERIAL']][] = $sub['BRANCH'];
}
foreach($result as $serial => $branches){
$unique = array_unique($branches);
if(count($unique) >1){
var_dump("ERROR: " . $serial, array_slice($unique,1));
}
}
Output:
string(13) "ERROR: qwerty"
array(2) {
[0]=>
string(5) "TEST2"
[1]=>
string(5) "TEST3" // I added that to test on multiple duplicates
}
Upvotes: 1
Reputation: 163297
One option could be using 2 foreach loops and check if SERIAL is the same and BRANCH is different.
If that is the case, break out of the loops or handle it accordingly.
foreach ($arrays as $arrayA) {
foreach ($arrays as $arrayB) {
if ($arrayA["SERIAL"] == $arrayB["SERIAL"] && $arrayA["BRANCH"] !== $arrayB["BRANCH"]) {
print_r($arrayB);
break 2;
}
}
}
See a php demo
Upvotes: 1