更新 CakePHP 中的记录(数组格式)

Update records in CakePHP (array format)

如何保存此类数据?它给了我

Array to String conversion error. 

我的 asc201516s_teachers table 有以下列:

我的数据数组是:

 [asc201516s_teachers] => Array
    (
        [teachers_name] => Array
            (
                [0] => asd asd 
                [1] => asd asd asd 
                [2] => asd asd asd asd 
            )

        [teachers_cnic] => Array
            (
                [0] => 32312-1212121-2
                [1] => 33434-3434343-4
                [2] => 34454-5454545-4
            )

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

        [teachers_contact] => Array
            (
                [0] => 1234-5678910
                [1] => 2345-6789101
                [2] => 3456-7891011
            )

    )

在CakePHP中保存多条记录的正确方法2.x如下:

$data=array(
    '0' => array(
        'teachers_name'=>'asd asd',
        'teachers_cnic'=>'32312-1212121-2',
        'teachers_gender'=>'1',
        'teachers_contact'=>'1234-5678910'
    ),
    '1' => array(
        'teachers_name'=>'asd asd asd',
        'teachers_cnic'=>'33434-3434343-4',
        'teachers_gender'=>'2',
        'teachers_contact'=>'2345-6789101'
        ),
    '2' => array(
        'teachers_name'=>'asd asd asd asd',
        'teachers_cnic'=>'34454-5454545-4',
        'teachers_gender'=>'2',
        'teachers_contact'=>'3456-7891011'
    )
);

$this->Teacher->saveMany($data);

您可以像这样创建您的表单字段,您可以将下面的代码放在循环中或其他替代方式中,以便您可以获得 ex:0,1,2 的 $key 变量的动态值, 3,4..等

echo $this->Form->input('modelName.' . $key . '.teachers_name', array());
echo $this->Form->input('modelName.' . $key . '.teachers_cnic', array());
echo $this->Form->input('modelName.' . $key . '.teachers_gender', array());
echo $this->Form->input('modelName.' . $key . '.teachers_contact', array());

提交表单后,您可以像这样在您的控制器中接收表单

$data=array(
    '0' => array(
        'teachers_name'=>'asd asd',
        'teachers_cnic'=>'32312-1212121-2',
        'teachers_gender'=>'1',
        'teachers_contact'=>'1234-5678910'
    ),
    '1' => array(
        'teachers_name'=>'asd asd asd',
        'teachers_cnic'=>'33434-3434343-4',
        'teachers_gender'=>'2',
        'teachers_contact'=>'2345-6789101'
        ),
    '2' => array(
        'teachers_name'=>'asd asd asd asd',
        'teachers_cnic'=>'34454-5454545-4',
        'teachers_gender'=>'2',
        'teachers_contact'=>'3456-7891011'
    )
);

然后就可以保存表单数据了,如下图所示

$this->Teacher->saveMany($data);

如果您需要更多信息,请告诉我, 如果您觉得此答案有用,请将此答案标记为可接受。