I'm having trouble mapping the object from database to display in my table. I have a table like this this in my database.
name total date
Awoc1 100 9/14/2022
Awoc1 200 9/15/2022
Awoc1 300 9/16/2022
Awoc2 100 9/14/2022
Awoc2 200 9/15/2022
Awoc2 300 9/16/2022
Awoc3 100 9/14/2022
Awoc3 200 9/15/2022
Awoc3 300 9/16/2022
And I fetch the data as objects like this, this is the response I get.
[
{ "total": "300", "date": "2022-09-14", "name": "AWOC1"},
{ "total": "200", "date": "2022-09-14", "name": "AWOC2"},
{ "total": "100", "date": "2022-09-14", "name": "AWOC3"},
{ "total": "300", "date": "2022-09-15", "name": "AWOC1"},
{ "total": "200", "date": "2022-09-15", "name": "AWOC2"},
{ "total": "100", "date": "2022-09-15", "name": "AWOC3"},
{ "total": "300", "date": "2022-09-16", "name": "AWOC1"},
{ "total": "200", "date": "2022-09-16", "name": "AWOC2"},
{ "total": "100", "date": "2022-09-16", "name": "AWOC3"},
]
What I was hoping to do is display the objects like this in a table. kind of horizontal.
9/14/2022 9/15/2022 9/16/2022
Awoc1 100 200 300
Awoc2 100 200 300
Awoc3 100 200 300
If I were you, I would create two variables. The first variable is a list of unique dates. The second is the data grouped by the name and date columns.
$data = json_decode('[
{ "total": "300", "date": "2022-09-14", "name": "AWOC1"},
{ "total": "200", "date": "2022-09-14", "name": "AWOC2"},
{ "total": "100", "date": "2022-09-14", "name": "AWOC3"},
{ "total": "300", "date": "2022-09-15", "name": "AWOC1"},
{ "total": "200", "date": "2022-09-15", "name": "AWOC2"},
{ "total": "100", "date": "2022-09-15", "name": "AWOC3"},
{ "total": "300", "date": "2022-09-16", "name": "AWOC1"},
{ "total": "200", "date": "2022-09-16", "name": "AWOC2"},
{ "total": "100", "date": "2022-09-16", "name": "AWOC3"}
]');
$data = collect($data);
$dates = $data->pluck('date')->unique();
// $dates Output:
//
// array:3 [▼
// 0 => "2022-09-14"
// 3 => "2022-09-15"
// 6 => "2022-09-16"
// ]
$transformedData = $data->groupBy('name')
->map(function ($item) {
return $item->groupBy('date')->flatten()->pluck('total', 'date');
});
// $transformedData Output:
//
// array:3 [▼
// "AWOC1" => array:3 [▼
// "2022-09-14" => "300"
// "2022-09-15" => "300"
// "2022-09-16" => "300"
// ]
// "AWOC2" => array:3 [▼
// "2022-09-14" => "200"
// "2022-09-15" => "200"
// "2022-09-16" => "200"
// ]
// "AWOC3" => array:3 [▼
// "2022-09-14" => "100"
// "2022-09-15" => "100"
// "2022-09-16" => "100"
// ]
// ]
return view('test', ['transformedData' => $transformedData, 'dates' => $dates]);
test.blade.php: (Think of it as a pseudo-code, you can easily convert it for Vue, React, or Angular)
<table>
<thead>
<tr>
<th></th>
@foreach($dates as $date)
<th>{{ $date }}</th>
@endforeach
</tr>
</thead>
@foreach($transformedData as $name => $totals)
<tr>
<td>{{ $name }}</td>
@foreach($totals as $total)
<td>{{ $total }}</td>
@endforeach
</tr>
@endforeach
</table>