2010-03-12 20 views
90

我有一個已知數量的列(例如頂部直徑,底部直徑,結構,顏色,數量)的PHP表單,但具有未知數量的行,因爲用戶可以根據需要添加行。通過POST提交一個多維數組與php

我已經發現瞭如何把每個字段(列)放到他們自己的數組中。

<input name="topdiameter['+current+']" type="text" id="topdiameter'+current+'" size="5" /> 
<input name="bottomdiameter['+current+']" type="text" id="bottomdiameter'+current+'" size="5" /> 

所以我結束了在HTML是:

<tr> 
    <td><input name="topdiameter[0]" type="text" id="topdiameter0" size="5" /></td> 
    <td><input name="bottomdiameter[0]" type="text" id="bottomdiameter0" size="5" /></td> 
</tr> 
<tr> 
    <td><input name="topdiameter[1]" type="text" id="topdiameter1" size="5" /></td> 
    <td><input name="bottomdiameter[1]" type="text" id="bottomdiameter1" size="5" /></td> 
</tr> 

...and so on. 

我想現在要做的就是把所有的行和列把它們放在一個多維數組和電子郵件的內容對客戶(最好是格式良好的表格)。我一直無法真正理解如何將所有這些輸入和選擇組合到一個不錯的數組中。

在這一點上,我將不得不嘗試使用幾個1D陣列,儘管我認爲使用單個2D陣列比使用幾個1D陣列更好。

回答

131

在提交,你會得到一個數組,如果是這樣創建的:

$_POST['topdiameter'] = array('first value', 'second value'); 
$_POST['bottomdiameter'] = array('first value', 'second value'); 

但是,我建議將您的表單名稱改爲這種格式:

name="diameters[0][top]" 
name="diameters[0][bottom]" 
name="diameters[1][top]" 
name="diameters[1][bottom]" 
... 

使用該格式,可以更容易地循環訪問這些值。

if (isset($_POST['diameters'])) 
{ 
    echo '<table>'; 
    foreach ($_POST['diameters'] as $diam) 
    { 
     // here you have access to $diam['top'] and $diam['bottom'] 
     echo '<tr>'; 
     echo ' <td>', $diam['top'], '</td>'; 
     echo ' <td>', $diam['bottom'], '</td>'; 
     echo '</tr>'; 
    } 
    echo '</table>'; 
} 
+0

謝謝!我已經開始接近這一點,儘管我已經翻轉了列和行。 – Fireflight 2010-03-15 13:32:53

+0

如果你是克隆文本字段,並且無法控制爲列表添加名字,比如'name =「diameters [0] [top]'如果我有多個名字,我該怎麼辦?例如top,bottom,左右?@DisgruntledGoat – 2017-03-24 15:35:41

15

,你可以用這樣的命名提交的所有參數:

params[0][topdiameter] 
params[0][bottomdiameter] 
params[1][topdiameter] 
params[1][bottomdiameter] 

再後來,你做這樣的事情:

foreach ($_REQUEST['params'] as $item) { 
    echo $item['topdiameter']; 
    echo $item['bottomdiameter']; 
}