Ranveer Singh Rajput
Ranveer Singh Rajput

Reputation: 21

How to insert multidimensional array in database using laravel

I have a multidimensional array which contains employee salaries according to salary year with its respective months. I want to insert salaries of different year at different row with their respective months values. I also have one year column and 12 months column in database table. Please guide me how should I insert salaries of employees at different row in table. My multidimensional array structure is like this:-

Array
(
    [2016] => Array
    (
        [jan] => 15000
        [feb] => 15000
        [mar] => 15000
        [apr] => 15000
        [may] => 15000
        [jun] => 15000
        [jul] => 15000
        [aug] => 15000
        [sep] => 15000
        [oct] => 15000
        [nov] => 15000
        [dec] => 15000
    )

    [2017] => Array
    (
        [jan] => 20000
        [feb] => 20000
        [mar] => 20000
        [apr] => 20000
        [may] => 20000
        [jun] => 20000
        [jul] => 20000
        [aug] => 20000
        [sep] => 20000
        [oct] => 20000
        [nov] => 20000
        [dec] => 20000
    )
)

Upvotes: 1

Views: 68

Answers (2)

shez1983
shez1983

Reputation: 34

Q. Why aren't you saving them (or saved them) at that point in time i.e Jan 2017? (but that's an aside q)

I would have a salaries' table with a date column (2016-01-01), user_id, and a salary (whether int, or float/double depending on if they are always integer or can be float).

In your example, it is a case of doing two loops:

foreach ($salaries as $year => $months) { 
    foreach ($months as $month => $salary) {
       // carbon parse to create a date 
       //insert into the table
    } 
}

Upvotes: 0

Vincent Decaux
Vincent Decaux

Reputation: 10714

You must flatten your array, you need an array like :

$data = [
   ['year'=>'2016', 'month'=>'1', 'salary' => 15000],
   ['year'=>'2016', 'month'=>'2', 'salary' => 15000],

   // ... and so on

Then you can just insert using your model like :

YourSalaryModel::insert($data);

Upvotes: 2

Related Questions