1

我有一段代码如下:

<td><?
    $days = array("Sun","Mon","Tue","Wed","Thur","Fri","Sat");
    for($i=1;$i<8;$i++)
    {
        echo $days[$i-1]?><input type="checkbox" name="labDays[]" value="<?=$days[$i]?>" checked="checked"><?
    }?>
</td>

但是,当我跑步时print_r($_REQUEST['labDays']);

我明白了Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => )

我期望Array ( [0] => Sun[1] => Mon[2] => Tue[3] => Wed[4] => Thur[5] => Fri[6] => Sat)

我确定这很愚蠢,但我不确定我错过了什么......

print_r($_REQUEST)呕吐物:Array ( [pg] => 12 [msg] => Facility Already Exist [facilityname] => kjgkjhgkjhg [facorgtype] => [facilitytype] => [administratorsname] => [divisionname] => [streetaddress1] => [streetaddress2] => [city] => [state] => [zipcode] => [phonenumber] => [faxnumber] => [email] => [mainstate] => [labDays] => Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => ) [facBillingContact] => [facBillingPhone] => [facBillingFax] => [facBillingRep] => [facBillingAccNum] => [facNotes] => [submit] => Create )

var_dump($_REQUEST['labDays'])

array
  0 => string 'Sun' (length=3)
  1 => string 'Mon' (length=3)
  2 => string 'Tue' (length=3)
  3 => string 'Wed' (length=3)
  4 => string 'Thur' (length=4)
  5 => string 'Fri' (length=3)
  6 => string 'Sat' (length=3)
4

3 回答 3

2

我相信这就是您正在寻找的:

    <?php
    $days = array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
    foreach ($days as $day) {
        echo <<<HTML
    <label>$day
        <input type="checkbox" name="labDays[]" value="$day" checked>
    </label>
HTML;

    }
    ?>

几点注意事项:

PHP

  • 不推荐使用简写语法(<? ?>尤其是)。<?= ?>
  • 对于迭代数组,foreach比 a 更适合for
  • 我对字符串使用 PHP 的 heredoc 语法。这样我就避免了引号混淆。
  • 使用$_POSTor$_GET而不是$_REQUEST,这样被认为更安全。

HTML

  • 在 HTML 中为表单元素使用标签,这会将文本与表单控件相关联,此外,当您单击文本时,它也会标记相应的复选框!
  • checked属性不需要任何值。它在那里就足够了。
于 2012-08-20T19:51:23.630 回答
1

如果你想遍历数组,foreach是最好的选择

$days = array("Sun","Mon","Tue","Wed","Thur","Fri","Sat");
foreach($days as $k=>$v)
{
    echo $k?><input type="checkbox" name="labDays[]" value="<?=$v?>" checked="checked"><?
}?>

使用for,您可以这样做:

$days = array("Sun","Mon","Tue","Wed","Thur","Fri","Sat");
for($i=0;$i<=6;$i++)
{
    echo $i;?><input type="checkbox" name="labDays[]" value="<?=$days[$i]?>" checked="checked"><?
}?>

推荐的方式..

$days = array("Sun","Mon","Tue","Wed","Thur","Fri","Sat");
foreach($days as $k=>$v)
{
    echo $k . ' <input type="checkbox" name="labDays[]" value="'.$v.'" checked="checked">'; //you can give your styles and css ofcourse to make it better..
}
于 2012-08-20T19:39:47.550 回答
-1

也许用echo打印值:

<input type="checkbox" name="labDays[]" value="<?php echo $days[$i]; ?>" checked="checked">
于 2012-08-20T19:52:55.343 回答