Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

PHP compare arrays and remove NOT matched objects

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

array_intersect_key is what you're looking for. It takes two or more arrays, and returns a new array containing the elements of the first array, whose keys are present in all provided arrays.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...