1

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
    )
)
1
  • Please share your migrations and models for these tables, and what you have tried for inserting thus far. Stack overflow is not a coding service. Commented Jul 13, 2020 at 13:20

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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
    } 
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.