CakePHP 2 Insert Multiple Rows from Array

3.5k Views Asked by At

How to insert to multiple row from array in CakePHP? This is my 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
    )

)

I have tried using foreach and for loop, but not working. Any idea? Thanks

3

There are 3 best solutions below

0
On BEST ANSWER

If your want to save the content of your Array

You can do it by

$data=$this->request->data;
saveAll($data, array('deep' => true)); 
0
On

I try using for loop, but it must start with 0 offset. How to keep it simple?

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); 
        } 
0
On

You need to arrange your data in following format

$dataToSave=array(

 [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
        )
    )

)

After this while saving data use

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