PHP:如何将一个数组中的键与另一个数组中的值进行比较,并返回匹配项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25472252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:51:01  来源:igfitidea点击:

PHP: How to compare keys in one array with values in another, and return matches?

phparrayscomparearray-differencearray-intersect

提问by Solace

I have the following two 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_onewhich 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_diffand array_intersect, but they compare values with values, and not the values of one array with the keys of the other.

我查看了array_diffand array_intersect,但它们将值与值进行比较,而不是将一个数组的值与另一个数组的键进行比较。

采纳答案by Skarpi Steinthorsson

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]);
    }
}

回答by Michel

As of PHP 5.1 there is array_intersect_key(manual).

从 PHP 5.1 开始,有array_intersect_key手册)。

Just flip the second array from key=>valueto value=>keywith array_flip()and then compare keys.

只需将第二个数组从key=>value翻转到value=>keywitharray_flip()然后比较键。

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.

根本不需要任何循环数组。

回答by garry towel

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);
  }
}

回答by Reimi Beta

<?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))); 
?>