2010-12-02 49 views
0

我有一個多層次樹形式的一對多關係。例如:複雜的PHP表單數據

Match -> Phase 1 -> Phase Property 1 
     -> Phase 1 -> Phase Property 2 

     -> Phase 2 -> Phase Property 1 
     -> Phase 2 -> Phase Property 2 
     -> Phase 2 -> Phase Property 3 

     -> Phase 3 -> Phase Property 1 
     -> Phase 3 -> Phase Property 2 

因此,在前端我能夠多階段比賽,很多相位特性添加到一個階段。

在PHP後端,我希望能夠在多維數組中表示這些數據,以便我可以遍歷所有階段,然後遍歷每個階段的屬性。理想情況下,我想遠離通過JavaScript管理ID /名稱。

我知道我可以使用這樣的事情在PHP收到一個數組:

<input type="text" name="phases[]" /> 

但是,我該如何繼續這種模式的性質?我可以做些什麼:

<input type="text" name="phaseProperties[][]" /> 

然後以某種方式「鏈接」每個屬性到正確的階段?

+0

phaseProperties [phase1] [] - 在向列表添加內容時動態地使用JS創建'phase1'。 – DampeS8N 2010-12-02 15:58:09

+0

那麼,它必須要求用JS管理階段ID?我希望我可以保持與相位相關的相位屬性,基於索引(0,1,2 ...) – 2010-12-02 16:00:18

回答

2

如果輸入字段出現在靜態頁面上,那麼您應該已經知道您要在服務器端輸入多少個字段。那麼,爲什麼使用像這樣的字段:

<input type="text" name="phaseProperties[0][]" /> 
<input type="text" name="phaseProperties[0][]" /> 
<input type="text" name="phaseProperties[1][]" /> 

這樣的壞事?如果這些字段是動態生成的(客戶端),那麼不應該有一個動態命名的問題。沒有明顯的原因,你似乎太過自制。

1

是的,你可以這樣做:

<input type="text" name="phaseProperties[Phase1][Property1]" /> 
<input type="text" name="phaseProperties[Phase1][Property2]" /> 
<input type="text" name="phaseProperties[Phase1][Property3]" /> 
<input type="text" name="phaseProperties[Phase2][Property1]" /> 
<input type="text" name="phaseProperties[Phase2][Property2]" /> 
<input type="text" name="phaseProperties[Phase2][Property3]" /> 

而在後端PHP,你會得到phaseProperties這樣的:

Array 
(
[Phase1] => Array 
(
[Property1] => a 
[Property2] => b 
[Property3] => c 
) 

[Phase1] => Array 
(
[Property1] => d 
[Property2] => e 
[Property3] => f 
) 

) 
1

不能使用(實際上你可以,但它不沒有幫助你)

<input type="text" name="phaseProperties[][]" /> 

因爲PHP無法知道你希望你的項目如何分組。它會將每個項目添加到一個單獨的組中。

Array 
(
    [0] => Array 
     (
      [0] => Item 1 
     ) 

    [1] => Array 
     (
      [0] => Item 2 
     ) 

    [2] => Array 
     (
      [0] => Item 3 
     ) 

    [3] => Array 
     (
      [0] => Item 4 
     ) 
) 

在參數中使用[]沒有什麼特別之處。它們的行爲與PHP中的[]運算符完全相同。例如:

$arr[][] = 'Item 1'; 
$arr[][] = 'Item 2'; 
$arr[][] = 'Item 3'; 
$arr[][] = 'Item 4'; 
print_r($arr); 

將具有我在上面發佈的相同輸出。

0

當您呈現UI(HTML)時,您可以使用php來循環並輸出輸入?

$phases = 3; 
$phasesProperty = array(
    array(1, 2), 
    array(1, 2, 3), 
    array(1, 2) 
); 

for($i = 0; $i < $phases; $i++) { 
    foreach($phasesProperty[$i] as $j) { 
     printf('<input type="text" name="Match[Phase%d][PhaseProperty%d]" />', $i, $j); 
    } 
}