我的控制器
public function showcart()
{
$da = isset($_COOKIE["cart"] ) ? $_COOKIE["cart"] : " []"。
$data = json_decode($da)。
return view('customer.showcart', compact('data')) 。
}
刀片:
<tbody>
@foreach ($data as $dat)
<form action="{{ url('/addcart') }}" method="post">
@csrf
<tr>
<td>{{ $dat['id'/span>] }}</td>
<td>{{ $dat['quantity'] }}</td>
</tr>
</form>
@endforeach>
</tbody>
當前輸出
{"id"/span>: ["8","8","8","9","9"。 "8","8","8","10"] ,"數量"。 ["3","2","3","3"。 "2","1","2","1","6"]}。
我想把這個轉換為JSON格式,每個索引如id[0]與數量[0],id[1]與數量[1]。
uj5u.com熱心網友回復:
如果你的目標是鍵/值對,那么請注意,一個物件不能有重復的鍵,由于你的id值是8、9或10(在例子中),輸出不能有超過3個鍵:
{"8"/span>: 1, "9": 2, "10": 6}。
無論如何,如果你的鍵在現實中確實是唯一的,那么你需要array_combine:
$arr = json_decode($da, true) 。
$data = array_combine($arr["id"], $arr[" quantity"])。)
注意,你對$da的賦值需要一個不同的默認情況,以使其兼容:
$da = isset($_COOKIE["cart"]) ? $_COOKIE["cart"] : '{"id":[], " quantity":[]}';
最后,你的回圈應該以不同的方式提取鍵和值:
<form action="{url('/addcart') }}" method="post">
@csrf
<table>
@foreach ($data as $key => $value)
<tr>
<td>{{ $key }}</td>
<td>{{ $value }}</td>
</tr>
@endforeach
</table>
</form>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/332257.html
標籤:
上一篇:在自定義物件陣列中找到一個專案并改變其值-SwifUI
下一篇:韌體的空中演算法
