Transforming a vertical table into a horizontal layout

I'm facing an issue with transforming the database object for table display. My database contains a table structured like this.

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

When fetching the data as objects, I receive the following response.

[
{ "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" },
{ &totquot;al": "100", "date": "2022-09-15", "name": "AWOC3" },
{ &qquotuot;total": "300", "date": "2022-09-16", "name": "AWOC1" },
{ &q"uot";total": "200", "date": "2022-09-16", "name": "AWOC2" },
{ &q"uo;total": "100", "date": "2022-09-16", "name": "AWOC3" },   
]

The goal is to showcase the objects in a horizontal table format like below.

        9/14/2022   9/15/2022   9/16/2022
Awoc1   100         200         300
Awoc2   100         200         300
Awoc3   100         200         300

Answer №1

If it were up to me, I'd suggest setting up two variables. The initial one would contain a collection of distinct dates, while the second one would hold data categorized 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: (This can be thought of as pseudo-code that adapts easily 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating the values of parent components in Vue.js 3 has been discovered to not function properly with composite API

Here is a Vue component I have created using PrimeVue: <template lang="pug"> Dialog(:visible="dShow" :modal="true" :draggable="false" header="My Dialog" :style="{ width: '50vw' }" ...

Using Laravel API authentication in middleware group for testing with Postman

Is there a way to test the API on Laravel that is defined within a middleware group? Route::group(['middleware' => 'auth:api'], function () { Route::post('/city/rating', 'API\HomeController@post_city_rating& ...

What steps can be taken to prolong the duration of a service?

As a newcomer to angularjs, I am struggling to find documentation or examples on how to extend a basic service in order to utilize its methods from other services. For example, consider the following basic service: angular.module('myServices', [ ...

Tips on how to retrieve the value of the second td in an HTML table when clicking on the first td utilizing jQuery

There is a specific requirement I have where I must retrieve the value of the second td in an HTML table when clicking on the first column. To accomplish this task, I am utilizing jQuery. $('.tbody').on('click','tr td:nth-child(1) ...

What exactly do bootstrap, javascript, jquery, and ajax entail?

Exploring the world of client-side scripting to enhance web page dynamism and data collection has piqued my interest. I have come across programming languages like JavaScript, Ajax, and jQuery. However, uncertainty clouds my understanding as concepts remai ...

Is there a way to incorporate vue samples into an independent HTML document?

Striving to broaden my knowledge of Vue, I set out to create a page with tabs inspired by one of the Vue examples available at . However, an obvious error seems to be eluding me, as I encounter a syntax issue on the line import * as Tabs from 'vue-s ...

What is the best way to add controllers to AngularJS?

What is the best way to troubleshoot this setup? app.js var app = angular.module('app', ['ui.router', 'app.controllers']); /* Why is FooCtrl not being recognized here? */ controllers.js var controllers = angular.module(&a ...

Find the correct file path for input using JavaScript or Angular 2

How can I retrieve the full file path of a selected Excel file using either pure JavaScript or Angular 2? I am looking to have the user select an Excel file, which will then be sent to a C# WEB API controller for further processing. Currently, my setup is ...

The method this.$el.querySelector does not exist

The data retrieved from the database is inserted into the input fields and submitted as a form. This data is an object that passes the value to the database. However, when I trigger this form, an error occurs. See example of the error <input id=" ...

Tips for implementing multiple middlewares in Next.js using the middleware.ts script

In the development of my Next.js project, I am exploring the implementation of multiple middleware without depending on external packages. Although I have seen examples of using a single middleware in Next.js with the next-connect package, I aim to achieve ...

Error message: The "spawn" function is not defined and is causing a TypeError to be thrown in

Having a bit of trouble here. I'm trying to make an async request using redux-thunk in my action creator, and the code looks like this: export const downloadFromYoutube = (download) => { console.log("Hello"); return dispatch => { va ...

Synchronize custom directive controller data with data from a factory

As a newcomer to angularjs, I stumbled upon this example that I found somewhere and it works perfectly well. However, I am puzzled by how the data within the customized directive controller remains synchronized with the factory data. Here is the snippet of ...

Sophisticated filter - Conceal Ancestry

Check out this snippet of my HTML: <td> <a class="button" href="#"> <input id="download">...</input> </a> <a class="button" href="#"> <input id="downloadcsv">...</input> </a> </td> I am ...

Adding embedded attributes from a different object

I am facing a challenge with two arrays called metaObjects and justObjects. These arrays consist of objects that share a common property called id. My goal is to merge properties from the objects in these separate arrays into a new array. const metaObje ...

Optimizing React components by efficiently updating props without triggering unnecessary renders

As I delve into learning React, I've encountered a challenge with using a component to display details of a selected item in a table. The issue arises when clicking "Next" on the paginated table, causing the state to update and re-render the component ...

Iterate through a JSON object using JavaScript, with distinct keys but the same object structure

Hello, I'm currently in the process of creating a slider using images sourced from a json file. Here is the json structure that I am working with: { "info":[ { "slide1":[ { "title" ...

Ways to minimize an array of objects by shared key values?

Suppose I have an array of objects structured like this: var jsonData = [ {"DS01":123,"DS02":88888,"DS03":1,"DS04":2,"DS05":3,"DS06":666}, {"DS01":123,"DS02":88888,"DS03":2,"DS04":3,"DS05":4,"DS06":666}, {"DS01":124,"DS02":99999,"DS03":3,"DS04" ...

Passing the value of a radio button to a component in React: a comprehensive guide

I've been struggling to figure out how to pass the value of a selected radio button to another component in React. Currently, I'm exploring the Star Wars API and attempting to create a basic search interface where users can retrieve information a ...

The modal disappears when the user clicks on the Previous/Next buttons of the jQuery UI datepicker

Using the jQuery datepicker from https://jqueryui.com/datepicker/ along with the UIkit framework found at I'm trying to incorporate the datepicker within a form that is inside a modal window. The issue arises when the modal window disappears after i ...

Instructions for activating a button in the absence of any inputs

I need help enabling a button in angularjs based on whether any of the inputs are filled out. I was successful in disabling a button when only one input is checked, but how can I do this for all inputs affecting one button? This is what I've attempted ...