I want to compare two arrays with each other and remove all objects from the first one who are NOT present in both arrays.
//array1
$apiData1 = [
'test1' => ["Volvo", "BMW", "Toyota"],
'test2' => ["Volvo", "BMW", "Toyota"],
'test3' => ["Volvo", "BMW", "Toyota"],
'test4' => ["Volvo", "BMW", "Toyota"],
'AAAAAAAAAAAAAAA' => ["Volvo", "BMW", "Toyota"],
];
// ======================
//array2
$apiData2 = [
'test1' => ["Volvo", "BMW", "Toyota"],
'test2' => ["Volvo", "BMW", "Toyota"],
'test3' => ["Volvo", "BMW", "Toyota"],
'test4' => ["Volvo", "BMW", "Toyota"],
'BBBBBBBBBBBBBBB' => ["Volvo", "BMW", "Toyota"],
];
The result should be array1 without the 'AAAAAAAAAAAAAAA' object.
//array1
$apiData1 = [
'test1' => ["Volvo", "BMW", "Toyota"],
'test2' => ["Volvo", "BMW", "Toyota"],
'test3' => ["Volvo", "BMW", "Toyota"],
'test4' => ["Volvo", "BMW", "Toyota"],
];
What I tried:
foreach ($apiData2 as $key => $value) {
if ((isset($apiData1[$key]) && !isset($apiData2[$key])) || (!isset($apiData1[$key]) && isset($apiData2[$key]))) {
unset($apiData1[$key]);
}
}
question from:
https://stackoverflow.com/questions/65857494/php-compare-arrays-and-remove-not-matched-objects