0

I have this array:

array:43 [▼
  "ALFA ROMEO" => array:1 [▼
    0 => "145"
  ]
  "AUDI" => array:6 [▼
    0 => "A1"
    1 => "A3"
    2 => "A4"
    3 => "A5"
    4 => "AUDI 80"
    5 => "Q3"
  ]
  "BMW" => array:15 [▼
    0 => "116I"
    1 => "118I"
    2 => "318I"
    3 => "318IA"
    4 => "320I"
    5 => "320IA"
    6 => "325I"
    7 => "328I"
    8 => "330I"
    9 => "535I"
    10 => "X1"
    11 => "X3"
    12 => "X5"
    13 => "X6"
    14 => "Z4"
  ]
]

I'd like to do this:

Get the key(ALFA ROMEO / AUDI / BMW) and search this key in a table (brands), get the id of this brand and iterate the "ALFA ROMEO" inside array to get the model (145) and insert in a new table called model_car(brand_id, model). And do the same to AUDI, BMW etc.

I know this is easy, but my mind does not work!

Thank you.

1
  • 3
    What have you already tried? Commented Dec 10, 2018 at 12:00

1 Answer 1

3

Try the code below this may help you to achieve what you wanted.

/* Let $array be the array posted by you. */
foreach ($array as $key => $data) {
    /* Fetch brand id by name. Assuming the name field replace it by your own. */
    $brand = Brands::where('name', $key)->first();

    /* Prepare array of brand id and model to be mass inserted. */
    $brandModel = [];
    foreach ($data as $i => $model) {
        $brandModel[$i]['brand_id'] = $brand->id;
        $brandModel[$i]['model'] = $model;
    }
    ModelCar::insert($brandModel);        //Insert into the new table model_car
}
Sign up to request clarification or add additional context in comments.

2 Comments

How did you know that Brands and ModelCar were classes, and how did you know his structure?
Welcome :) @PiterOrtiz

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.