I have 02 arrays of different length and different elements. Arrays are as follows
$activeRsrvs = [{"reservation_reservationid":"KHAN2016Q221","hotelrooms_hotelroomsid":"1","status":"active"},{"reservation_reservationid":"KHAN2016Q223","hotelrooms_hotelroomsid":"3","status":"active"}]
$allRooms = [{"hotelroomsid":"1","roomno":"01"},{"hotelroomsid":"2","roomno":"02"},{"hotelroomsid":"3","roomno":"50"},{"hotelroomsid":"4","roomno":"15"}]
My code is as follows:
foreach($activeRsrvs as $actvRsrv)
{
foreach($allRooms as $room)
{
if($actvRsrv['hotelrooms_hotelroomsid'] !== $room['hotelroomsid'])
{
$output[] = $room;
} //end if
} //end inner loop
}//end outer loop
The result which it generates is as follows:
[{"hotelroomsid":"2","roomno":"02"},{"hotelroomsid":"3","roomno":"50"},{"hotelroomsid":"4","roomno":"15"},{"hotelroomsid":"1","roomno":"01"},{"hotelroomsid":"2","roomno":"02"},{"hotelroomsid":"4","roomno":"15"}]
But I want it should return the following result:
[{"hotelroomsid":"2","roomno":"02"},{"hotelroomsid":"4","roomno":"15"}]
The loop erroneously results 6 elements and i want only 02 elements be returned. Kindly help me.
I think the easiest way is to add all rooms to a temp array and then unset them in the loop if they exist in the temp array
Edit: Copy to Paste Solution ;)
$tmp = array();
foreach($allRooms as $room) {
$tmp[$room['hotelroomsid']] = $room;
}
foreach($activeRsrvs as $actvRsrv)
{
foreach($allRooms as $room)
{
if($actvRsrv['hotelrooms_hotelroomsid'] === $room['hotelroomsid'])
{
if(array_key_exists($room['hotelroomsid'], $tmp)) {
unset($tmp[$room['hotelroomsid']]);
}
} //end if
} //end inner loop
}//end outer loop
$output = array_values($tmp);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.