我有2个数组,我试图找出应该检查哪些复选框,哪些不是。我确实得到了正确的结果,但是如果要检查2个复选框,我会得到2组复选框,如果要检查3,我会得到3组复选框等等...我做了很多次尝试以避免使用break并继续陈述,没有成功。
以下是代码:
<?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 :(得分: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 . '/>';
}
?>
答案 1 :(得分:0)
这可以减少到几行(n.b.我已经重新格式化,以便更容易阅读SO):
<?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 } ?>
注意用于回显statement()结果的短语法以及if语句的短语法(condition?true output:false output)