循环不同长度的阵列

时间:2016-05-24 13:41:17

标签: php arrays loops

我有02个不同长度和不同元素的数组。数组如下

$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"}]

我的代码如下:

foreach($activeRsrvs as $actvRsrv)
{
    foreach($allRooms as $room)
    {
        if($actvRsrv['hotelrooms_hotelroomsid'] !== $room['hotelroomsid'])
        {
            $output[] = $room;
        } //end if
    } //end inner loop
}//end outer loop

它产生的结果如下:

[{"hotelroomsid":"2","roomno":"02"},{"hotelroomsid":"3","roomno":"50"},{"hotelroomsid":"4","roomno":"15"},{"hotelroomsid":"1","roomno":"01"},{"hotelroomsid":"2","roomno":"02"},{"hotelroomsid":"4","roomno":"15"}]

但我希望它应该返回以下结果:

[{"hotelroomsid":"2","roomno":"02"},{"hotelroomsid":"4","roomno":"15"}]

循环错误地导致6个元素,我想只返回02个元素。请帮助我。

1 个答案:

答案 0 :(得分:1)

我认为最简单的方法是将所有房间添加到临时数组中,然后如果它们存在于临时数组中则在循环中取消设置它们

编辑:复制到粘贴解决方案;)

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