PHP使用foreach获取复选框的值

我有一个包含日期的复选框列表。这是我到目前为止的预览:


// This code gets all the Sunday's in a month:

 function getSundaysForTheMonth($y, $m)

    {

        return new DatePeriod(

            new DateTime("first sunday of $y-$m"),

            DateInterval::createFromDateString('next sunday'),

            new DateTime("last day of $y-$m 23:59:59")

        );

    }


这就是我显示它的方式:


 // Get current Year and Month

    $currentYear = date('Y');

    $currentMonth = date('m');


    // Get month name

    $beginMonthName = date("F", mktime(0, 0, 0, $currentMonth, 10));



    echo "Select which Sunday(s) of the month of ". $beginMonthName . ". $currentYear . " ": \n<BR>";

    $i=0;


    // Display all Sundays for 3 months

    foreach (getSundaysForTheMonth($currentYear, $currentMonth) as $sunday) {

        $thisSunday = $sunday->format("m - d - Y");

        echo "<input type=\"checkbox\" name=\"date".$i."\" value=\".$thisSunday. \">".$thisSunday."<BR>";

        $i++;

    }

这个想法是用 foreach 而不是这种方式来做:


<input type="checkbox" name="date0" value="2020-04-12 ">2020-04-12<BR>

<input type="checkbox" name="date1" value="2020-04-12 ">2020-04-19<BR>

<input type="checkbox" name="date2" value="2020-04-12 ">2020-04-26<BR>

<input type="checkbox" name="date3" value="2020-04-12 ">2020-03-03<BR>

现在我正在尝试获取这些值。我认为代码应该看起来与此类似但有点不同,因为输入名称具有不同的名称(date0、date1、date2,...)。


<?php


if (isset($_POST['date'])) {


    foreach ($date as $sunday){

        echo $sunday."<br />";

        // Store $sunday in an array

    }

} else {

    echo "No selections";

}

?>

关于如何使这项工作有任何想法?

我的目标是将它存储在一个数组中,其中将被放入数据库中。谢谢。


墨色风雨
浏览 122回答 1
1回答

凤凰求蛊

您可以为您的复选框使用数组输入名称,然后这将在 PHP 中转换为数组:foreach (getSundaysForTheMonth($currentYear, $currentMonth) as $sunday) {&nbsp; &nbsp; $thisSunday = $sunday->format("m - d - Y");&nbsp; &nbsp; echo "<input type=\"checkbox\" name=\"date[]\" value=\"$thisSunday\">$thisSunday<BR>";}这会产生以下输出 ( demo ):<input type="checkbox" name="date[]" value="04 - 05 - 2020">04 - 05 - 2020<BR><input type="checkbox" name="date[]" value="04 - 12 - 2020">04 - 12 - 2020<BR><input type="checkbox" name="date[]" value="04 - 19 - 2020">04 - 19 - 2020<BR><input type="checkbox" name="date[]" value="04 - 26 - 2020">04 - 26 - 2020<BR>在 PHP 中,您将得到一个数组 (in $_POST['date']),它看起来像(例如,如果选中了第一个和第三个复选框):Array (&nbsp; &nbsp; [0] => '04 - 05 - 2020'&nbsp; &nbsp; [1] => '04 - 19 - 2020')请注意,如果您要将这些值插入到数据库中,您应该将它们放入正确的 ISO-8601 格式 ( YYYY-MM-DD),因此将foreach循环更改为如下所示:foreach (getSundaysForTheMonth($currentYear, $currentMonth) as $sunday) {&nbsp; &nbsp; $thisSunday = $sunday->format("m - d - Y");&nbsp; &nbsp; echo "<input type=\"checkbox\" name=\"date[]\" value=\"" . $sunday->format('Y-m-d') . "\">$thisSunday\n<BR>";}
打开App,查看更多内容
随时随地看视频慕课网APP