![](/img/trans.png)
[英]How can I access an individual key and value from an array using a foreach loop in PHP?
[英]How can I set individual variables in a PHP loop from form?
例如:我有一個基本的 HTML 表格,如下所示:
<div class="form-group">
<label class="control-label" for="checkboxes" name="industry">How would you classify your business?</label>
<div class="checkbox">
<label for="checkboxes-0">
<input type="checkbox" name="checkboxes" id="checkboxes-0">
Nonprofit
</label>
</div>
<div class="checkbox">
<label for="checkboxes-1">
<input type="checkbox" name="checkboxes" id="checkboxes-1">
Service
</label>
</div>
這只是一個片段它不是完整的形式
我想將多選表單解析為 PHP 中的變量。 對於“Nonprofit”、“Service”等形式中的每個名稱,如果用戶選擇“Nonprofit”,我想為 nonprofit 創建一個變量並將其設置為 1,並使“service”的變量等於 0 .
我知道我必須使用這樣的循環
if(isset($_POST['submit'])) {
$industry = $_POST['checkboxes'];
}
但是如何循環遍歷標簽並將用戶選擇的變量設置為 1 並使 rest 等於 0?
單程。 首先為每個可以被復選框覆蓋的隱藏輸入定義一個隱藏輸入,每個都需要一個name
和value
:
<input type="hidden" name="Nonprofit" value="0">
<input type="checkbox" name="Nonprofit" id="checkboxes-0" value="1">
<input type="hidden" name="Service" value="0">
<input type="checkbox" name="Service" id="checkboxes-1" value="1">
然后您可以訪問$_POST['Nonprofit']
,其值為0
或1
等...
另一種方式,知道可以提交什么是提交一個數組:
<input type="checkbox" name="check[Nonprofit]" id="checkboxes-0" value="1">
<input type="checkbox" name="check[Service]" id="checkboxes-1" value="1">
然后將提交的內容與0
數組合並:
$checks = ['Nonprofit' => 0, 'Service' => 0];
$checks = array_merge($checks, $_POST['check']);
然后您可以訪問$checks['Nonprofit']
,其值為0
或1
等...
您可以通過更改 html 中的一些內容並制作一組用戶選擇的選項來實現所需的 output,我們可以通過這些選項對其進行迭代。
HTML
<form method="post">
<div class="form-group">
<label class="control-label" for="checkboxes" name="industry">How would you classify your business?</label>
<div class="checkbox">
<label for="checkboxes-0">
<input type="checkbox" name="nonprofit" id="checkboxes-0" value="nonprofit">
Nonprofit
</label>
</div>
<div class="checkbox">
<label for="checkboxes-1">
<input type="checkbox" name="service" id="checkboxes-1" value="service">
Service
</label>
</div>
<button type="submit" name="submit">Submit</button>
</div>
</form>
PHP
if (isset($_POST['submit'])) {
foreach ($_POST as $key => $value) {
if ($value != null) {
$result[] = $value;
}
}
foreach ($result as $value1) {
$values[] = $value1;
}
foreach ($values as $value2) {
echo '$'.$value2.'= 1<br>';
}
}
Output
如果用戶選擇Nonprofit
$nonprofit= 1
如果選擇了Service
$service= 1
如果兩者都被選中
$nonprofit= 1
$service= 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.