2017-06-28 90 views
0

我有任意數量的'行'數據,我需要通過表單發佈,以實現以下數組結構,以便impact_speed將包含x個數組,每個數組包含descriptionvalueunit元素:Post form input as seperate arrays

array(1) { 
    ["impact_speed"]=> 
    array(3) { 
    [0]=> 
    array(3) { 
     ["description"]=> 
     string(3) "one" 
     ["value"]=> 
     string(2) "10" 
     ["unit"]=> 
     string(3) "mph" 
    } 
    [1]=> 
    array(3) { 
     ["description"]=> 
     string(3) "two" 
     ["value"]=> 
     string(2) "20" 
     ["unit"]=> 
     string(3) "kph" 
    } 
    [2]=> 
    array(3) { 
     ["description"]=> 
     string(5) "three" 
     ["value"]=> 
     string(2) "30" 
     ["unit"]=> 
     string(3) "fps" 
    } 
    } 
} 

如果行的數量是固定的,我可以通過索引我的形式投入像這樣實現這一點:但是

<input type="text" name="impact_speed[0][description]" value="one"> 
<input type="text" name="impact_speed[0][value]" value="10"> 
<input type="text" name="impact_speed[0][unit]" value="mph"> 

<input type="text" name="impact_speed[1][description]" value="two"> 
<input type="text" name="impact_speed[1][value]" value="20"> 
<input type="text" name="impact_speed[1][unit]" value="kph"> 

<input type="text" name="impact_speed[2][description]" value="three"> 
<input type="text" name="impact_speed[2][value]" value="30"> 
<input type="text" name="impact_speed[2][unit]" value="fps"> 

,我加入這些USI允許用戶點擊加號圖標創建新行的JavaScript UI,因此我沒有固定數量的行來處理。

例如,如果我不指定一個像下面的例子索引號,它顯然產生每行3個單獨的陣列,這是不是我想要的:

<input type="text" name="impact_speed[][description]" value="three"> 
<input type="text" name="impact_speed[][value]" value="30"> 
<input type="text" name="impact_speed[][unit]" value="fps"> 

有我的命名形式的一種方式輸入而不必動態插入索引號(0,1,2等)?

+0

什麼是你的Javascript是什麼樣子? – Koralarts

回答

0

我最終編制了我的數組索引,因爲我意識到這是做這件事的唯一可行的方法。然後我每增加一行就增加索引。這是用於在行被克隆後增加索引的代碼示例。

// If the input names contain an array index, we need to increment it: 
 
$newRow.find('input, select').each(function(){ 
 
    $(this).attr('name', $(this).attr('name').replace(/\[([0-9]+)\]/, function(match, capture) { 
 
    return '[' + (parseInt(capture, 10) + 1) + ']' ; 
 
    })); 
 
});