CakePHP 2从数组插入多行

时间:2015-06-09 23:50:34

标签: php arrays cakephp cakephp-2.0

如何从CakePHP中的数组插入多行?这是我的print_r($ _ POST)

Array ( 
[category] => Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
        [3] => 4
        [4] => 5
    )

[surface_area] => Array
    (
        [0] => 1
        [1] => 2
        [2] => 24
        [3] => 342
        [4] => 235
    )

[tree_area] => Array
    (
        [0] => 252
        [1] => 254
        [2] => 252
        [3] => 635
        [4] => 457
    )

[no_of_tree] => Array
    (
        [0] => 457
        [1] => 658
        [2] => 3563
        [3] => 6357
        [4] => 363
    )

我尝试过使用foreach和for循环,但没有工作。任何的想法? 感谢

3 个答案:

答案 0 :(得分:1)

如果您想保存数组的内容

你可以通过

来完成
$data=$this->request->data;
saveAll($data, array('deep' => true)); 

答案 1 :(得分:0)

我尝试使用for循环,但必须以0偏移量开始。如何保持简单?

for($i = 0; $i < count($this->request->data['category']); $i++) { 

            $this->Model->create();
            $data[0] = array(
                'project_id' => $id, 
                'criteria_form_list_id' => $category[0]['category'], 
                'surface_area' => $surface_area[0]['surface_area'], 
                'cover_by_tree' => $tree_area[0]['tree_area'], 
                'no_of_tree' => $no_of_tree[0]['no_of_tree']
            );
            $data[$i] = array(
                'project_id' => $id, 
                'criteria_form_list_id' => $category[$i]['category'], 
                'surface_area' => $surface_area[$i]['surface_area'], 
                'cover_by_tree' => $tree_area[$i]['tree_area'], 
                'no_of_tree' => $no_of_tree[$i]['no_of_tree']
            );

            $this->Model->save($data); 
        } 

答案 2 :(得分:0)

您需要按以下格式排列数据

$ dataToSave =阵列(

 [0]=>array(

    [ModelName]=>array(
            field1=>value1,
            field2=>value2
        )
    )
[1]=>array(

    [ModelName]=>array(
            field1=>value3,
            field2=>value4
        )
    )
[2]=>array(

    [ModelName]=>array(
            field1=>value5,
            field2=>value6
        )
    )
[3]=>array(

    [ModelName]=>array(
            field1=>value7,
            field2=>value8
        )
    )

此后保存数据使用

$this->ModelName->saveall($dataToSave);