phparraysmultidimensional-arrayfilterintersection

Get intersecting rows from two 2d arrays


I am trying to get the intersection of two or more arrays with this kind of structure:

First array:

array(
    [0] => array(
        ['room_id'] => 21
        ['room_name'] => 'GB 101'
        ['capacity'] => 40
    )
    [1] => array(
        ['room_id'] => 22
        ['room_name'] => 'H 114'
        ['capacity'] => 20
    )
    [2] => array(
        ['room_id'] => 23
        ['room_name'] => 'GB 203'
        ['capacity'] => 20
    )
    [3] => array(
        ['room_id'] => 25
        ['room_name'] => 'H 100'
        ['capacity'] => 30
    )
    [4] => array(
        ['room_id'] => 26
        ['room_name'] => 'GB 206'
        ['capacity'] => 40
    )
)

Second Array:

array(
    [0] => array(
        ['room_id'] => 21
        ['room_name'] => 'GB 101'
        ['capacity'] => 40
    )
    [1] => array(
        ['room_id'] => 23
        ['room_name'] => 'GB 203'
        ['capacity'] => 20
    )
    [2] => array(
        ['room_id'] => 26
        ['room_name'] => 'GB 206'
        ['capacity'] => 40
    )
)

Resulting array:

array(
    [0] => array(
        ['room_id'] => 21
        ['room_name'] => 'GB 101'
        ['capacity'] => 40
    )
    [1] => array(
        ['room_id'] => 23
        ['room_name'] => 'GB 203'
        ['capacity'] => 20
    )
    [2] => array(
        ['room_id'] => 26
        ['room_name'] => 'GB 206'
        ['capacity'] => 40
    )
)

I tried using array_intersect_assoc to get the intersection using the following code:

$result = call_user_func_array('array_intersect_assoc', $arrays);

It does the trick but it gives the following warning which is expected according here:

A PHP Error was encountered

Severity: Notice

Message: Array to string conversion

I am making an Ajax based system so the error messes it up. Is there any way to get the intersection of the arrays?


Solution

  • Try serializing them:

    $result = array_map('unserialize',
                  array_intersect(
                      array_map('serialize', $first), array_map('serialize', $second)));