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?
Try serializing them:
$result = array_map('unserialize',
array_intersect(
array_map('serialize', $first), array_map('serialize', $second)));
array_map()
runs each sub-array of the main arrays through serialize()
which converts each sub-array into a string representation of that sub-array
array_intersect()
now has a one-dimensional array for each of the arrays to comparearray_map()
runs the array result (intersection) through unserialize()
to turn the string representations back into sub-arrays