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

Can I retrieve a variable within the watch() function in Vue?

Is there a way to access variable asd in the watch() function and clear the interval when it's complete? I've tried the code below but the timer goes into negative values. Are there any possible solutions? methods:{ testing(){ this. ...

Is it possible to switch the hamburger menu button to an X icon upon clicking in Vue 3 with the help of PrimeVue?

When the Menubar component is used, the hamburger menu automatically appears when resizing the browser window. However, I want to change the icon from pi-bars to pi-times when that button is clicked. Is there a way to achieve this? I am uncertain of how t ...

Get a CSV file through EmberJs

I have been experimenting with various function calls, but I am unable to figure out how to initiate a CSV download in EmberJs. Below is the most recent code I have tried: let endpoint = '/api/foo/'; let options = { url: endpoint, type: ...

The steps to implement an onchange function for displaying image previews in a profile image tag

Within my code, there is a profile image tag along with an input tag for updating the image. I aim to implement a functionality that allows me to select a new image and automatically update the profile picture when it changes <div class="col-sm-6"> ...

Implementing Express 4: The Correct Way to Serve Routes from External Files

Something about my Express 4 application is causing me frustration. Here's the configuration: routes/profile.js var express = require('express'); var router = express.Router(); router.get('/profile', function(req, res) { res.s ...

As the cursor moves, the image follows along and rotates in sync with its

Can anyone help me figure out how to create a moving image that follows the mouse cursor? I have a radial pie menu with an image in the middle, and I want it to spin and rotate as the mouse moves. Any ideas on how I can achieve this effect? I would greatl ...

What is the best way to interact with Redis without using any external modules?

I am curious about the communication process between the node redis wrapper and the RESP (REdis Serialization Protocol) database. Here is a simple example: const redis = function(uri) { this.client = '' // How do we establish a connection wit ...

JavaScript loop to target a specific item

My goal is to animate the correct div under each navigation item, rather than all of them with the "navItemUnder" class. You can see exactly what I mean by hovering over a navigation item in this codePen. I am looking for a solution to target only one lin ...

What's the process for setting a value in selectize.js using Angular programmatically?

Currently, I am implementing the AngularJS directive to utilize selectize.js from this source: https://github.com/kbanman/selectize-ng In my scenario, I have two dropdowns and my goal is to dynamically populate one of them called selectizeVat based on the ...

Generating URL parameters for Ajax requests on the fly

My current project involves creating a dynamic form where the number of fields displayed changes based on the user's selection from a dropdown menu. This means that depending on what option they choose, anywhere from 2 to 20 different fields may be sh ...

How to grab JSON data within a CakePHP 2.2 controller

Trying to transmit JSON data from a web page using JQuery, as shown below: $.ajax({ type: "post", url: "http://localhost/ajax/login", data: '{username: "wiiNinja", password: "isAnub"}', dataType: "json", contentType: "applica ...

Opening a modal in React Material UI from an autocomplete component results in losing focus

My current challenge involves utilizing the material-ui library to create an autocomplete feature where each item is clickable and opens a modal window. The basic structure looks like this: const ModalBtn = () => { ... return ( <> ...

When the visitor is browsing a particular page and comes across a div element, carry out a specific action

I am trying to determine if I am currently on a specific page and, if so, check if a certain div exists in that page. Here is what I know: To check if a specific page exists, I can use the code if('http://'+location.hostname+location.pathname+& ...

Dynamic Formatting with Vue JS: Enhancing Phone Number Input

I am working on a form that includes a phone number input field, and I want the formatting of the number to change to a standard telephone number format as the user types. Can someone provide guidance on how this can be achieved using JavaScript and Vue 3? ...

Exploring the optimal approach for distinguishing between numbers and strings in a JavaScript/Typescript class

I recently encountered a situation with my Typescript/React solution where I defined a property as a number and set the input type to "number", but when the state value was placed in an input field, it would change to a string unless properly handled. In ...

Leveraging configuration files in AngularJS

I'm working on an Angular application that communicates with a Node.js backend Express application. I am using a config file to store environment variables for my Node app. Here's how I access the config file in my Node app: index.js var port = ...

Continuously running loop to retrieve data

I've been working on a function that retrieves data from the backend and then assigns it to the state for display in a web browser. Although everything seems to be functioning correctly, I've noticed that every time I make a request, the function ...

Several directories for viewing in Node.js with Express

I have been researching different solutions, but I am still unsure about how to effectively integrate Express with multiple view folders. Imagine an Express application divided into distinct parts, each organized in its own subfolder: app +partA + ...

Error: Unable to retrieve the 'id' property from an undefined object (View: /home/rimonet2/boostbuy.ng/resources/views/admin/pages/dashboard.blade.php)

After logging into my admin dashboard, an error exception is displayed. The problem was identified in this specific line of code: ...

Is there a way for me to assign values to my array within each loop when the inner elements vary?

Every time I work on this JavaScript code, I feel like I'm close to finishing it but then encounter another obstacle. My goal is to extract values from different elements such as <input type="text"> and <select>. Here's the code snipp ...