PHP:如何比较一个数组中的键与另一个数组中的值,并返回匹配项? [英] PHP: How to compare keys in one array with values in another, and return matches?

查看:805
本文介绍了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

我看过 array_diff

code>和 array_intersect ,但是它们将值与值进行比较,而不是一个数组的值与另一个的键的值。

解决方案

如果我正确理解这一点:



返回一个新数组:

  $ array_new = []; 
foreach($ array_two as $ key)
{
if(array_key_exists($ key,$ array_one))
{
$ array_new [$ key] = $ array_one [$ key];
}
}

剥离$ array_one:

  foreach($ array_one as $ key => $ val)
{
if(array_search($ key,$ array_two) === false)
{
unset($ array_one [$ key]);
}
}


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_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)

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.

解决方案

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:

foreach($array_one as $key => $val)
{
    if(array_search($key, $array_two) === false)
    {
        unset($array_one[$key]);
    }
}

这篇关于PHP:如何比较一个数组中的键与另一个数组中的值,并返回匹配项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆