array_intersect,但用于单个数组变量的子数组

时间:2023-01-20 12:11:54

I've got an array that looks like this:

我有一个这样的数组:

$foo = array(
    0 => array('a', 'b', 'c', 'd'),
    1 => array('b', 'c', 'd'),
    2 => array('b', 'd', 'f')
)

I'll refer to $foo[0], $foo[1], and $foo[2] as sub-arrays.

我将引用$foo[0]、$foo[1]和$foo[2]作为子数组。

I basically need to perform an array_intersect() across all 3 sub-arrays in $foo. The result should be:

我基本上需要在$foo中对所有3个子数组执行array_intersect()。结果应该是:

array('b', 'd')

As all three sub-arrays had these values in common. What is the best way to do this?

因为所有三个子数组都有这些值。最好的方法是什么?

Some considerations:

一些注意事项:

  • There will always be at least one sub-array. No upper limit.
  • 总会有至少一个子数组。没有上限。
  • If only one sub-array is provided, it should return that sub-array
  • 如果只提供了一个子数组,那么它应该返回该子数组
  • If there aren't any common values in all the sub-arrays, an empty array should be returned
  • 如果所有子数组中没有任何公共值,则应该返回一个空数组
  • If this functionality already exists as a PHP function, I will /facepalm
  • 如果这个功能已经作为PHP函数存在,我将/facepalm

1 个解决方案

#1


24  

$intersect = call_user_func_array('array_intersect',$foo);

Note that keys are preserved from $foo[0]

注意,键从$foo[0]保存

#1


24  

$intersect = call_user_func_array('array_intersect',$foo);

Note that keys are preserved from $foo[0]

注意,键从$foo[0]保存