简体   繁体   English

Laravel,将数据从数组保存到数据库

[英]Laravel, save data from array to database

I need to save data from this array to MySQL database 我需要将数据从这个数组保存到MySQL数据库

0 => {#517 ▼
    +"id": 59
    +"name": "example_name_1"
    +"category": "category_1"
    +"price": 100
    +"description": "example_description_1"
}
1 => {#516 ▼
    +"id": 60
    +"name": "example_name_2"
    +"category": "category_2"
    +"price": 200
    +"description": "example_description_2"
}

I am tryinig to save like this, but reveive errors like 我试着像这样保存,但是像我这样的错误

Undefined index: name 未定义的索引:名称

for ($idx = 0; $idx < count($products); $idx++)
{
    $values = new Product();
    $values->name = $products["name"][$idx];
    $values->category= $products["category"][$idx];
    $values->description = $products['description'][$idx];
    $values->price = $products['price'][$idx];
    $values->save();
}

You get that error because the order you accessed the array is incorrect. 您收到该错误,因为您访问该数组的顺序不正确。

The order should be the which product index and then name, category or whichever field. 订单应该是产品索引,然后是名称,类别或任何字段。

for ($idx = 0; $idx < count($products); $idx++)
{
    $values = new Product();
    $values->name = $products[$idx]["name"];
    $values->category= $products[$idx]["category"];
    $values->description = $products[$idx]['description'];
    $values->price = $products[$idx]['price'];
    $values->save();
}

Or you can easily use a foreach as @VincentDecaux mentioned in his comment. 或者你可以轻松地使用foreach作为@VincentDecaux在评论中提到的。

foreach ($products as $product) {
    $values = new Product();
    $values->name = $product["name"];
    $values->category= $product["category"];
    $values->description = $product['description'];
    $values->price = $product['price'];
    $values->save();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM