关联数组,迭代键和值PHP LARAVEL

我有这个数组:

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"
  ]
]

我想这样做:

获取密钥( ALFA ROMEO / AUDI / BMW )并在表(品牌)中搜索此密钥,获取此品牌的 id 并迭代"ALFA ROMEO" inside数组以获取模型( 145 )并插入名为model_car的新表(brand_id) ,模型) . 并对奥迪,宝马等做同样的事情 .

我知道这很容易,但我的思想不起作用!

谢谢 .

回答(1)

2 years ago

尝试下面的代码可以帮助您实现您想要的 .

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