2015-07-12 72 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