[英]PHP: How to compare keys in one array with values in another, and return matches?
I have the following two arrays:我有以下两个 arrays:
$array_one = array('colorZero'=>'black', 'colorOne'=>'red', 'colorTwo'=>'green', 'colorThree'=>'blue', 'colorFour'=>'purple', 'colorFive'=>'golden');
$array_two = array('colorOne', 'colorTwo', 'colorThree');
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_one
的数组,它只包含键是 $array_two 成员的键值对(通过创建一个新数组或从$array_one
)
How can I do that?我怎样才能做到这一点?
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.我查看了array_diff
和array_intersect
,但它们将值与值进行比较,而不是将一个数组的值与另一个数组的键进行比较。
As of PHP 5.1 there is array_intersect_key
( manual ). 从PHP 5.1开始,有array_intersect_key
( 手动 )。
Just flip the second array from key=>value to value=>key with array_flip()
and then compare keys. 只需使用array_flip()
将第二个数组从key => value翻转到value => key ,然后比较键。
So to compare OP's arrays, this would do: 因此,为了比较OP的数组,这将做:
$result = array_intersect_key( $array_one , array_flip( $array_two ) );
No need for any looping the arrays at all. 根本不需要任何循环数组。
If I am understanding this correctly: 如果我正确理解这一点:
Returning a new array: 返回一个新数组:
$array_new = [];
foreach($array_two as $key)
{
if(array_key_exists($key, $array_one))
{
$array_new[$key] = $array_one[$key];
}
}
Stripping from $array_one: 从$ array_one中剥离:
foreach($array_one as $key => $val)
{
if(array_search($key, $array_two) === false)
{
unset($array_one[$key]);
}
}
Tell me if it works: 告诉我它是否有效:
for($i=0;$i<count($array_two);$i++){
if($array_two[$i]==key($array_one)){
$array_final[$array_two[$i]]=$array_one[$array_two[$i]];
next($array_one);
}
}
<?php $array_one = array('colorZero'=>'black', 'colorOne'=>'red', 'colorTwo'=>'green', 'colorThree'=>'blue', 'colorFour'=>'purple', 'colorFive'=>'golden'); $array_two = array('colorOne', 'colorTwo', 'colorThree'); print_r(array_intersect_key($array_one, array_flip($array_two))); ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.