Reputation: 321
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();
}
Upvotes: 1
Views: 4863
Reputation: 5124
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();
}
Upvotes: 4