Get intersection of a multiple array in PHP

前端 未结 3 1397
有刺的猬
有刺的猬 2021-01-13 22:22

Starting Point

I have a multiple array, like the follow example.

$array = array (
  \'role_1\' => 
  array (
    0 => \'value_2\',
    1 =>         


        
相关标签:
3条回答
  • 2021-01-13 22:28

    You should be able to do

    call_user_func_array('array_intersect', $array_of_arrays)
    

    This will pass each element of your array of arrays as an argument to array_intersect, which takes a variable number of arrays as arguments and returns their intersection.

    0 讨论(0)
  • 2021-01-13 22:38

    array_intersect work for this:

    $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 = array_intersect($data['role_1'], $data['role_2'], $data['role_3']);
    print_r($result);
    

    result :

    Array ( [0] => value_2 ) 
    
    0 讨论(0)
  • 2021-01-13 22:41

    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 will help spread the elements of your array as parameters inside array_intersect.

    0 讨论(0)
提交回复
热议问题