PHP:如何将一个数组中的键与另一个数组中的值进行比较,并返回匹配项?
我有以下两个数组:
$array_one = array('colorZero'=>'black', 'colorOne'=>'red', 'colorTwo'=>'green', 'colorThree'=>'blue', 'colorFour'=>'purple', 'colorFive'=>'golden');
$array_two = array('colorOne', 'colorTwo', 'colorThree');
我想要一个来自 $array_one
的数组,它只包含键是 $array_two 成员的键值对(通过创建一个新数组或删除其余的$array_one
)
I want an array from $array_one
which only contains the key-value pairs whose keys are members of $array_two (either by making a new array or removing the rest of the elements from $array_one
)
我该怎么做?
我查看了 array_diff
和 array_intersect
,但它们将值与值进行比较,而不是将一个数组的值与另一个数组的键进行比较.
I looked into array_diff
and array_intersect
, but they compare values with values, and not the values of one array with the keys of the other.
推荐答案
更新
查看 Michel 的答案:https://stackoverflow.com/a/30841097/2879722.这是一个更好、更简单的解决方案.
Check out the answer from Michel: https://stackoverflow.com/a/30841097/2879722. It's a better and easier solution.
原答案
如果我理解正确:
返回一个新数组:
$array_new = [];
foreach($array_two as $key)
{
if(array_key_exists($key, $array_one))
{
$array_new[$key] = $array_one[$key];
}
}
从 $array_one 中剥离:
Stripping from $array_one:
foreach($array_one as $key => $val)
{
if(array_search($key, $array_two) === false)
{
unset($array_one[$key]);
}
}
相关文章