比较嵌套foreach中的数组值

时间:2016-01-27 10:52:28

标签: php arrays

我有两个阵列:

$rooms = [1,2,3,4,5,6,7,8,9];
$reserved_rooms = [4, 7]; 

我想像这样打印这个数组:

1
2
3
Room 4 is reserved
5
6
Room 7 is reserved

她是我的代码:

$rooms = [1,2,3,4,5,6,7,8,9];
$reserved_rooms = [4, 7]; 

foreach($rooms as $key=>$val){
    foreach($reserved_rooms as $val2){
        if($val == $val2){
            echo $val2." room is reserved";
        }   
        else
            echo $val."<br>";
    }
}

结果是:

1
1
2
2
3
3
4 room is reserved4
5
5
6
6
7
7 room is reserved8
8
9
9

5 个答案:

答案 0 :(得分:3)

使用in_array()检查数组中是否存在值。

foreach($rooms as $room) {
   if( in_array($room, $reserved_rooms) ) {
      echo $room .' is reserved.' . PHP_EOL;
      continue;
   }
   echo $room . PHP_EOL;
}

https://eval.in/508706

答案 1 :(得分:3)

您需要将echo移出循环。

$rooms = [1,2,3,4,5,6,7,8,9];
$reserved_rooms = [4, 7]; 

foreach($rooms as $key=>$val){
    $isReserved = false; // add this

    foreach($reserved_rooms as $val2){
        if($val == $val2){
            $isReserved = true;
            break; // is reserved, no need to check the other values
        }
    }

    if ($isReserved) { // now decide whether it is reserved or not
        echo $val." room is reserved";
    } else {
        echo $val."<br>";
    }
}

答案 2 :(得分:1)

如果您不想使用in_array()功能:

$rooms = [1,2,3,4,5,6,7,8,9];
$reserved_rooms = [4, 7]; 

array_map(function ($room) use ($reserved_rooms) { 
    foreach($reserved_rooms as $reserved_room) {
       if ($reserved_room == $room) { 
           print "Room $room is reserved\n";
           return;
       }
    }
    print "$room\n"; 
}, $rooms);

https://eval.in/508743

答案 3 :(得分:0)

你应该试试这个:

foreach($rooms as $key=>$val){
    if(in_array($val, $reserved_rooms){
        echo $val." room is reserved";
    }else{
        echo $val
    }
}

答案 4 :(得分:0)

$rooms = [1,2,3,4,5,6,7,8,9];
$reserved_rooms = [4, 7]; 

foreach($rooms as $key=>$val){
    $flag = false;
    foreach($reserved_rooms as $val2){
        if($val == $val2){
            echo "Room ".$val2." is reserved<br />";
            $flag=true;
            break;
        }        
    }
    if($flag == false){
        echo $val."<br />";
    }
}