如何在PHP中使用循环使发送数据到post数组更有效


How to use loops to make sending data to a post array more efficent in PHP

我想请求一些帮助,通过使用循环使我的代码更高效。在进入代码之前,让我先描述一下下面的场景。

我正在开发一个会议调度应用程序,用户通过复选框输入他们的可用性,这些复选框连接到其中有40个时隙。我想使用循环来提高下面3段代码的效率。

第一节

$id1 = $_POST ['id1'];
$id2 = $_POST ['id2'];
etc etc etc
$id40 = $_POST ['id40'];

SECTION2

if (isset ($_POST ['slot1'])) $slot1 = 1; else $slot1 = 0;
if (isset ($_POST ['slot2'])) $slot2 = 1; else $slot1 = 0;
etc etc etc
if (isset ($_POST ['slot40'])) $slot40 = 1; else $slot1 = 0;

第三节

$sql = "INSERT INTO individualavailability (slotID, uniNum, available) VALUES 
('$id1', '$uniNum', '$slot1'),
('$id2', '$uniNum', '$slot2'),
etc etc etc
('$id40', '$uniNum', '$slot40')";

Stefan的想法很适合复选框。当你有一些数字或字符串-你可以。

<?php
foreach($_POST as $key => $value)
{
    $esc_key = strtolower(trim($key);
    if (substr($esc_key), 0, 2) === 'id') {
        isset($_POST[$key]) ? $ids[] = intval(trim($value)); : $ids[] = 0;
    }
}

为什么不将输入"分组"?

<input type="checkbox" name="slot[]" value="40" />
<input type="checkbox" name="slot[]" value="41" />

在PHP中可以这样做

foreach($_POST['slot'] as $value)
{
}