[英]Add a key in array even value is empty PHP
我有一個表單,其中可以是幾行輸入相同的幾次,像這樣,
<input type="text" name="company[]"><input type="text" name="type[]">
<input type="text" name="company[]"><input type="text" name="type[]">
<input type="text" name="company[]"><input type="text" name="type[]">
現在我必須將這些字段輸入到數據庫中,因此我循環輸入字段並且工作正常。
但我有一個問題:有時循環中的字段可能是空的。 即公司將有價值但不是類型。 那么我怎樣才能讓循環在一個鍵中輸出空值,如下所示:
Array(
company => array(
[0] => string0
[1] => string1
[2] => string2
)
type => array(
[0] =>
[1] => string1
[2] => string2
)
)
所以你可以看到類型的第一個鍵是空的,那么我怎么能實現呢,
我試圖這樣做,但沒有結果,
$postFields = array('company', 'type');
$postArray = array();
foreach($postFields as $postVal){
if($postVal == ''){
$postArray[$postVal] = '';
}
else {
$postArray[$postVal] = $_POST[$postVal];
}
}
感謝任何幫助,
這個HTML:
<input type="text" name="company[]"><input type="text" name="type[]">
將動態填充數組的鍵。 我想你永遠不會得到一個空的0
元素,只要提交了一個文本字段。 相反,您最終會得到不匹配的數組長度,您將無法確定哪個數字被省略。
解決方案是在HTML中明確說明鍵,如下所示:
<input type="text" name="company[0]"><input type="text" name="type[0]">
<input type="text" name="company[1]"><input type="text" name="type[1]">
<input type="text" name="company[2]"><input type="text" name="type[2]">
現在,您可以循環遍歷數組,如果未設置某個鍵,則可以將其設置為空字符串:
foreach( range( 0, 2) as $i) {
if( !isset( $_POST['company'][$i]))
$_POST['company'][$i] = "";
if( !isset( $_POST['type'][$i]))
$_POST['type'][$i] = "";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.