2015-07-12 28 views
2

将数据发送给后阵列比较有效,我想寻求一些帮助使我的代码要通过使用循环更有效。在进入代码之前,让我描述下面的场景。如何使用循环,以使PHP

我发展,用户通过它连接到时隙,其中有40我想用循环,使代码更有效以下3个部分的复选框进入它们的可用性会议调度应用。

第1

$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; 

第3节

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

etc etc etc 

('$id40', '$uniNum', '$slot40')"; 

回答

1

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; 
    } 
} 
1

你为什么不 '团' 的投入?

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

在PHP中,你可以做那么

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

非常感谢斯特凡和Koredalin,您的帮助非常感谢....我会在今晚给您的建议一个尝试! – Rodger123