我有一个包含一对多关系的多层树的表单。例如:
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 :(得分:2)
如果输入字段出现在静态页面上,那么您应该已经知道要在服务器端输入多少输入字段。那么为什么要使用以下字段:
<input type="text" name="phaseProperties[0][]" />
<input type="text" name="phaseProperties[0][]" />
<input type="text" name="phaseProperties[1][]" />
这么糟糕的事情?如果字段是动态(客户端)生成的,那么动态命名它们应该没有问题。你似乎没有明显的理由限制自己。
答案 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
)
)
答案 2 :(得分: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);
将具有我在上面发布的相同输出。
答案 3 :(得分: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);
}
}