在PHP中获取多个数组的交集 [英] Get intersection of a multiple array in PHP

查看:715
本文介绍了在PHP中获取多个数组的交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多重数组,如以下示例所示.

I have a multiple array, like the follow example.

$array = array (
  'role_1' => 
  array (
    0 => 'value_2',
    1 => 'value_3',
  ),
  'role_2' => 
  array (
    0 => 'value_1',
    1 => 'value_2',
  ),
  'role_3' => 
  array (
    0 => 'value_2',
    1 => 'value_3',
  ),
)

目标

我喜欢循环遍历子数组以仅得到交集.该数组是动态创建的,可以有很多子数组role_[x],并且在子数组内还有很多键/值.键不是必需的,只有值.密钥也是一个计数,而不是字符串.

Goal

I like to loop about the sub-arrays to get only the intersection. The array was created dynamically, can have a lot of sub-arrays role_[x] and also a lot of key/value inside the sub-arrays. The key is not necessary, only the value. The key is also a count, not a string.

因此,我希望在此示例中获得这个小阵列.

As result I like to get in this example this small array.

$array = array( 'value_2' )

与子数组的role_1相似,索引"array-name"在相交后不再相关.对于我来说,重要的是结果是值,每个子数组中都只存在一个值.

The index, "the array-name", like role_1 of the sub-arrays is not more relevant after intersection. Important for me in the result is the values, only the values there are existed in each sub-array.

我尝试过使用源代码,但是我认为这可能更简单.

I had tried with the source, but I think it is possible much simpler.

$value_stack = array();
$result = array();
$i = 0;
foreach( $settings_ as $role => $values ) {

    foreach( $values as $value ){

        if( in_array( $value,$value_stack ) || $i === 0 ) {
            $result[ $role ][] = $value;
        }

        $value_stack[] = $value;
    }
    $i++;

};

此多数组结果的合并应在循环中以array_merge运行.

The merge of this multi array result should run with a array_merge in a loop.

感谢您的时间.

推荐答案

您可以使用 array_intersect 涵盖动态$data这样的内容:

You can use array_intersect to cover the dynamic $data as such:

$data = array (
  'role_1' => 
  array (
    0 => 'value_2',
    1 => 'value_3',
  ),
  'role_2' => 
  array (
    0 => 'value_1',
    1 => 'value_2',
  ),
  'role_3' => 
  array (
    0 => 'value_2',
    1 => 'value_3',
  )
);

$result = call_user_func_array('array_intersect', $data);

call_user_func_array 将有助于传播您的元素数组作为array_intersect中的参数.

call_user_func_array will help spread the elements of your array as parameters inside array_intersect.

这篇关于在PHP中获取多个数组的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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