2014-07-02 71 views
-1

我有2個數組,我試圖找出哪些複選框應該檢查,哪些不是。我確實得到了正確的結果,但是如果應該檢查2個複選框,我會得到2組複選框,如果選中3個複選框,我會得到3組複選框,等等......我做了很多次嘗試以避免使用中斷並繼續聲明,沒有成功。2個陣列內的循環

下面是代碼:

<?php 
foreach ($rooms as $room) { 
    foreach ($searchQuerySelectedRooms as $selRoom) { 
     if ($room['roomID'] != $selRoom) { 
?> 
<input type="checkbox" name="rooms[]" value="<?php echo $room['roomID']; ?>" style="float:left;width:20px; margin-right:10px;"/> 
<?php 
     } else { 
?> 
<input type="checkbox" name="rooms[]" value="<?php echo $room['roomID']; ?>" style="float:left;width:20px; margin-right:10px;" checked="checked"/> 
<?php                 
     } 
    } 
} 
?> 

陣列$rooms打印以下:

Array 
(
[0] => Array 
    (
     [roomID] => 2 
     [hotelID] => 10 
     [roomtypeID] => 1 
     [roomNumber] => 1 
    ) 

[1] => Array 
    (
     [roomID] => 3 
     [hotelID] => 10 
     [roomtypeID] => 1 
     [roomNumber] => 2 
    ) 

[2] => Array 
    (
     [roomID] => 4 
     [hotelID] => 10 
     [roomtypeID] => 2 
     [roomNumber] => 3 
    ) 
[3] => Array 
    (
     [roomID] => 5 
     [hotelID] => 10 
     [roomtypeID] => 2 
     [roomNumber] => 4 
    ) 
) 

雖然陣列$searchQuerySelectedRooms打印以下:

Array 
(
    [0] => 2 
    [1] => 3 
    [2] => 4 
) 

任何幫助將十分讚賞。

的問候,約翰

+0

請張貼您的陣列 –

+0

當然...我會在一分鐘內更新帖子...對不起 – user2417624

+0

問題已更新... – user2417624

回答

2

請檢查該代碼

<?php 
foreach ($rooms as $room) { 
    if (in_array($room['roomID'], $searchQuerySelectedRooms)) { 
     $checker = 'checked="checked"'; 
    } else { 
     $checker = ''; 
    } 

    echo '<input type="checkbox" name="rooms[]" value="' . $room['roomID'] . '" style="float:left;width:20px; margin-right:10px;" ' . $checker . '/>'; 

} 
?> 
+0

就像一個魅力......謝謝 – user2417624

0

這可以減少到只有幾行(注:我已經重新格式化,以使其更容易因此,閱讀):

<?php foreach ($rooms as $room) { ?> 
    <input type="checkbox" 
      name="rooms[]" 
      value="<?= $room['roomID']; ?>" 
      style="float:left;width:20px; margin-right:10px;" 
      <?= in_array($room['roomID'], $searchQuerySelectedRooms)? 'checked="checked"':''?>/> 
<?php } ?> 

。注意到短語法呼應的聲明(的結果),也爲一個if語句的語法短(條件爲真輸出:錯誤的輸出)