问题
How would I compare 2 Arrays in PHP to find which values each array have in common.
Example would be
Array 1
Array
(
[0] => ace
[1] => one
[2] => five
[3] => nine
[4] => elephant
)
Array 2
Array
(
[0] => elephant
[1] => seven
[2] => ace
[3] => jack
[4] => queen
)
Output Array ( [0] => ace [1] => elephant )
回答1:
array_intersect function can do this.
回答2:
PHP has an array_intersect() function that can do this. As an example, ypo can put the following code into PHPFiddle for testing:
<?php
$array1 = array('ace', 'one', 'five', 'nine', 'elephant');
$array2 = array('elephant', 'seven', 'ace', 'jack', 'queen');
print_r($array1); print('<br>');
print_r($array2); print('<br>');
print_r(array_intersect($array1, $array2)); print('<br>');
?>
Then you'll see that it gives you what you want (reformatted for readability):
Array ( [0] => ace
[1] => one
[2] => five
[3] => nine
[4] => elephant )
Array ( [0] => elephant
[1] => seven
[2] => ace
[3] => jack
[4] => queen )
Array ( [0] => ace
[4] => elephant )
Do note that this does not actually give you consecutive keys in the result, the keys appear to come from the first array given to array_intersect()
. If it's important that you get a consecutively-indexed array, you may need a post-processing step to adjust it. Something like this should be a good start (modification to original fiddle to use consecutive indexes):
<?php
$array1 = array('ace', 'one', 'five', 'nine', 'elephant');
$array2 = array('elephant', 'seven', 'ace', 'jack', 'queen');
print_r($array1); print('<br>');
print_r($array2); print('<br>');
$array3 = array();
foreach (array_intersect($array1, $array2) as $val) {
array_push($array3, $val);
}
print_r($array3); print('<br>');
?>
回答3:
If you're in a language where there is no built-in intersection, but you have hashes, you just add all the elements of one array into the hash and then go through the second array checking to see if they are in the hash you just built up.
This is all of if you don't care about order. If you care about order, it's just a for loop seeing if a[i] == b[i]
来源:https://stackoverflow.com/questions/4065431/compare-2-arrays-for-likeness