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

时间:2018-12-10 11:58:09

标签: php arrays laravel associative

我有这个数组:

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 / 宝马)并在表格( brands )中搜索此密钥>),获取该品牌的 id ,并在数组中迭代“ ALFA ROMEO”以获取模型( 145 ),然后插入名为model_car(brand_id,模型)。并对AUDI,BMW等进行相同操作。

我知道这很简单,但是我的思想却无法正常工作!

谢谢。

1 个答案:

答案 0 :(得分:2)

尝试下面的代码可以帮助您实现所需的目标。

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