问题
Suppose we have two arrays:
$a=array('1'=>'Apple','2'=>'Microsoft',
'3'=>'Microapple','4'=>'Applesoft','5'=>'Softapple');
$b=array(1,3);
Where $b array represents the keys of array $a to be differentiated against.
And we expect to receive another array $c with the following values:
$c=array('2'=>'Microsoft','4'=>'Applesoft','5'=>'Softapple');
In php manual there are two functions:
array_diff($array1,$array2); //difference of values
array_diff_key($array1,$array2);//difference of keys
But neither of the above is applicable here.
What should we do?
Edit
Thanks everyone for contribution.
I performed some benchmarks on two arrays predefined as follows:
for ($i=0; $i < 10000; $i++) { //add 10000 values
$a[]=mt_rand(0, 1000000); //just some random number as a value
}
for ($i=0; $i < 10000; $i++) { //add 10000 values as keys of a
$b[]=mt_rand(0, 1000);
} //randomly from 0 to 1000 (eg does not cover all the range of keys)
Each test was also taken 10000 times, the average time of Nanne
's solution was:
0.013398
And the one of decereé
:
0.014865
Which is also excellent.
...Unlike some other suggestion with in_array() but (that answer was deleted):
foreach ($a as $key => $value)
if (!in_array($key, $b))
$c[$key] = $value;
The above did 2 seconds on average. For the obvious reason that in_array() would have to loop through the $b to check whether the value existed. The above is an excellent example how not
to do it! :-)
回答1:
I would just code it like:
$c = $a;
foreach ($b as $removeKey) {
unset($c[$removeKey]);
}
回答2:
$c = array_diff_key($a, array_flip($b));
回答3:
Your array $b isn't setting array keys, you are setting values.
If you were to use:
$a=array('1'=>'Apple','2'=>'Microsoft',
'3'=>'Microapple','4'=>'Applesoft','5'=>'Softapple');
$b=array('1' => NULL ,'3' => NULL);
array_diff_key($a,$b)
You would get the result you predict.
来源:https://stackoverflow.com/questions/11936898/php-array-difference-against-keys-of-an-array-and-an-array-of-keys