简体   繁体   中英

Laravel, save data from array to database

I need to save data from this array to MySQL database

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 ($products as $product) {
    $values = new Product();
    $values->name = $product["name"];
    $values->category= $product["category"];
    $values->description = $product['description'];
    $values->price = $product['price'];
    $values->save();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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