通过form post将数组或数组的数组从视图发送到控制器动作


YII send array or array of array from view to controller action via form post

我有一个关于两种不同类型数据的问题。

我在Yii中有一个视图,它有一个表单控件。我想发送一个数组,一个数组的数组到控制器,到我的create action。

数组为:$arraySons = ('albert','francis','rupert');

数组的数组是$arrayFather = ('1'=>array(6,7,8));

我必须使用一些控件,所以表单将在$_POST中发布它?…或者这不能做,我必须使用JavaScript?

通常,在HTML表单中,您可以通过使用多个具有相同名称的字段和数组符号来创建数组。

<input name="sons[]">
<input name="sons[]">

当你提交表单$_POST['sons']将是一个数组,并可以处理如下:

foreach ($_POST['sons'] as $son) {
    echo 'Son of the father is '.$son."'n";
}

您可以按照@crafter的答案创建表单。我只是写了更多的细节:

<input type="hidden" name="sons[]" value="albert">
<input  type="hidden" name="sons[]" value="rupert">

等等

对于父亲,你会做类似的事情:

<input  type="hidden" name="father[1][]" value="6">
<input  type="hidden" name="father[1][]" value="7">
<input  type="hidden" name="father[1][]" value="8">

但是如果用户不需要看到数据,你可以用数据准备一个JSON对象,并将其发布在1个字段中,这对我来说似乎更容易

<input  type="hidden" name="father" value="<?= json_encode($arrayFather); ?>">
<input  type="hidden" name="sons" value="<?= json_encode($arraySons); ?>">

然后在您的操作中,您可以从post获取数据并使用json_decode

解码它
$myArrayFather = json_decode($_POST['father']);
$myArraySons = json_decode($_POST['sons']);