my controller
public function showcart()
{
$da = isset($_COOKIE["cart"]) ? $_COOKIE["cart"] : "[]";
$data = json_decode($da);
return view('customer.showcart', compact('data'));
}
blade:
<tbody>
@foreach ($data as $dat)
<form action="{{ url('/addcart') }}" method="post">
@csrf
<tr>
<td>{{ $dat['id'] }}</td>
<td>{{ $dat['quantity']}}</td>
</tr>
</form>
@endforeach
</tbody>
current output
{"id":["8","8","8","9","9","8","8","8","10"],"quantity":["3","2","3","3","2","1","2","1","6"]}
I want to convert this in JSON with each of the indexes like id[0] with quantity[0], id[1] with quantity [1].
CodePudding user response:
If you aimed for key/value pairs, then please be aware that an object cannot have duplicate keys, and since your id
values are 8, 9, or 10 (in the example), the output could not have more than 3 keys:
{"8": 1, "9": 2, "10": 6}
Anyway, if your keys are indeed unique in reality, then you need array_combine
:
$arr = json_decode($da, true);
$data = array_combine($arr["id"], $arr["quantity"]);
Note that your assignment to $da
needs a different default case to make it compatible:
$da = isset($_COOKIE["cart"]) ? $_COOKIE["cart"] : '{"id":[],"quantity":[]}';
Finally, your loop should extract the key and value differently:
<form action="{{ url('/addcart') }}" method="post">
@csrf
<table>
@foreach ($data as $key => $value)
<tr>
<td>{{ $key }}</td>
<td>{{ $value }}</td>
</tr>
@endforeach
</table>
</form>