如何使用来自另一个数组的值作为键从数组中选择值的子集?(复制)

时间:2022-03-03 21:24:43

This question already has an answer here:

这个问题已经有了答案:

Here's my array of $keys:

这是我的$keys数组:

Array
(
    [0] => 1
    [1] => 3
    [2] => 4
)

And my $values:

和我的价值观:美元

Array
(
    [0] => Red
    [1] => Orange
    [2] => Yellow
    [3] => Green
    [4] => Blue
)

I want to create a new array of some of the values in $values using the values in $keys as keys:

我想用$keys中的值作为键,创建一个新的$值数组:

Array
(
    [1] => Orange
    [3] => Green
    [4] => Blue
)

Obviously I can foreach to get the values I want, but I want to make sure I'm not overlooking something in the plethora of PHP array functions.

显然,我可以foreach来获得我想要的值,但是我想确保我没有忽略PHP数组函数中的一些东西。

I've Googled the question, and the answer comes back as using array_combine, which won't achieve the desired output.

我在谷歌上搜索了这个问题,得到的答案是使用array_combine,它不能实现所需的输出。

Your help is appreciated :)

感谢您的帮助。

1 个解决方案

#1


5  

Flip the $keys array to make the values keys and then use array_intersect_key():

翻转$keys数组来创建值键,然后使用array_intersect_key():

$result = array_intersect_key($values, array_flip($keys));

Returns the values from $values that have the same keys as the flipped $keys.

返回与翻转的$keys具有相同键的$值的值。

#1


5  

Flip the $keys array to make the values keys and then use array_intersect_key():

翻转$keys数组来创建值键,然后使用array_intersect_key():

$result = array_intersect_key($values, array_flip($keys));

Returns the values from $values that have the same keys as the flipped $keys.

返回与翻转的$keys具有相同键的$值的值。