Get intersection of multiple arrays in PHP

starting point

I have several arrays, as in the following example.

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

purpose

I like to quote about sub-arrays to only get intersection. The array was created dynamically, it can have many sub-arrays role_[x], as well as many key / values ​​inside sub-arrays. The key is not needed, only the value. The key is also a number, not a string.

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

$array = array( 'value_2' )

Array-name indexes, such as role_1sub-arrays, are no longer relevant after the intersection. As a result, the values ​​are important to me, only the values ​​there exist in each sub-range.

Try

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

$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 .

.

+4
3

array_intersect $data :

$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.

+3

call_user_func_array('array_intersect', $array_of_arrays)

array_intersect, .

+5

array_intersect :

$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);

:

Array ( [0] => value_2 ) 
+1

All Articles