[英]Laravel - Pass value and key of array to database
我目前在結帳網站時遇到問題。 我需要將 arrays 的值和鍵傳遞給數據庫,但我不知道如何從數組中獲取它們。
用於將其傳遞給數據庫的代碼:
foreach ($request->toArray() as $key => $value)
{
// dd($request->toArray());
$ordered_ticket = new OrderedTickets();
$ordered_ticket->checkout_id = $uuid;
ordered_ticket->ticket_id = // should be the key of the array
$ordered_ticket->amount = // should be the value of the array
$ordered_ticket->price = 100;
$ordered_ticket->save();
}
像這樣遍歷嵌套數組
foreach ($request->toArray() as $key => $value)
{
if($key === 'ticket'){
foreach($value as $ticketId => $ticketValue)
$ordered_ticket = new OrderedTickets();
$ordered_ticket->checkout_id = $uuid;
$ordered_ticket->ticket_id = $ticketId; // should be the key of the array
$ordered_ticket->amount = $ticketValue; // should be the value of the array
$ordered_ticket->price = 100;
$ordered_ticket->save();
}
}
}
或者更簡單:
foreach ($request->toArray()['ticket'] as $key => $value)
{
$ordered_ticket = new OrderedTickets();
$ordered_ticket->checkout_id = $uuid;
$ordered_ticket->ticket_id = $key; // should be the key of the array
$ordered_ticket->amount = $value; // should be the value of the array
$ordered_ticket->price = 100;
$ordered_ticket->save();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.