亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

PHP使用foreach獲取復選框的值

PHP使用foreach獲取復選框的值

PHP
墨色風雨 2022-12-11 10:16:37
我有一個包含日期的復選框列表。這是我到目前為止的預覽:// 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,...)。<?phpif (isset($_POST['date'])) {    foreach ($date as $sunday){        echo $sunday."<br />";        // Store $sunday in an array    }} else {    echo "No selections";}?>關于如何使這項工作有任何想法?我的目標是將它存儲在一個數組中,其中將被放入數據庫中。謝謝。
查看完整描述

1 回答

?
鳳凰求蠱

TA貢獻1825條經驗 獲得超4個贊

您可以為您的復選框使用數組輸入名稱,然后這將在 PHP 中轉換為數組:


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

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

    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 (

    [0] => '04 - 05 - 2020'

    [1] => '04 - 19 - 2020'

)

請注意,如果您要將這些值插入到數據庫中,您應該將它們放入正確的 ISO-8601 格式 ( YYYY-MM-DD),因此將foreach循環更改為如下所示:


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

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

    echo "<input type=\"checkbox\" name=\"date[]\" value=\"" . $sunday->format('Y-m-d') . "\">$thisSunday\n<BR>";

}


查看完整回答
反對 回復 2022-12-11
  • 1 回答
  • 0 關注
  • 158 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號