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?
Advertisement
Answer
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 }