Using PHP to generate a table populated with generic elements from an array

How can I create a dynamic table in PHP that can handle any generic array with different keys and values, including nested arrays? I want to use the same table structure for various arrays regardless of their content. Any advice on achieving this flexibility would be greatly appreciated.

Here is an example of an array hardcoded into the PHP table code:

{
    "port": "Et2",
    "name": "**Description**",
    "status": "connected",
    "vlan": "in",
    "duplex": "Po301",
    "speed": "full",
    "type": "10G   10GBASE-CR"
},

I envision the table code being able to adapt to any generic array like the one below. If a value is another array, I want all its contents to be displayed in a single table cell, even if it wraps to multiple lines. The array could potentially contain hundreds of values.

{
    "key1": "value 1",
    "key2": "value 2",
    "key3": "value 3",
    "key4": ["value 1a","value 2a","value 3a"]
},

Currently, I am using the following code to populate a table with specific array elements. However, I aim to enhance the table code to support outputting data from various network commands.

for($i = 0; $i < sizeof($data); $i++)
{
    $temp .= "<tr>";
    $temp .= "<td>" . $data[$i]["port"] . "</td>";
    $temp .= "<td>" . $data[$i]["name"] . "</td>";
    $temp .= "<td>" . $data[$i]["status"] . "</td>";
    $temp .= "<td>" . $data[$i]["vlan"] . "</td>";
    $temp .= "<td>" . $data[$i]["duplex"] . "</td>";
    $temp .= "<td>" . $data[$i]["speed"] . "</td>";
    $temp .= "<td>" . $data[$i]["type"] . "</td>";
    $temp .= "</tr>";
}

/*End tag of table*/
$temp .= "</table>";

/*Printing temp variable which holds table*/
echo $temp;

Answer №1

Iterate through the array of arrays using this method

$output .= "<table>";
foreach ($array as $sub){
    $output .= "<tr>";
    foreach ($subArray as $key => $value) {
        $output .= "<td>" . $value . "</td>";  
    }
    $output .= "</tr>";
}
$output .= "</table>";

Answer №2

After incorporating suggestions from both @RiggsFolly and @WOUNDEDStevenJones, I decided to merge their insights. In the second foreach loop, I added a condition to check if the $val variable is an array. If it is indeed an array, I used the implode function to convert it into a string format. Many thanks for your help!

$temp .= "<table>";
foreach ($data as $subArray){
    $temp .= "<tr>";
    foreach ($subArray as $key => $val) {
        if (is_array($val)) { #new if
                $val = implode(", ",$val); #new if
                } #new if
        $temp .= "<td>" . $val . "</td>";
    }
    $temp .= "</tr>";
}
$temp .= "</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

How about incorporating AJAX into your HTML code?

I am currently in the process of developing an email system for a company that wishes to use it for sending emails. To achieve this, I have implemented a custom HTML editor for creating email content. My goal is to post the email contents to an external PH ...

JavaScript combined with a dynamic menu, a customized current link style using CSS, and a site built on PHP

Here's my current website setup: My website is modular and uses dynamic inclusion. The header is a crucial part of the main page, which is responsible for displaying content from specific links on the site. External links to CSS and js files are incl ...

Combining ASP.NET MVC with HTML5 for dynamic web development

We are in the process of planning a new project and are interested in utilizing ASP.NET with the MVC pattern. Additionally, we want to incorporate the new features of HTML5. However, we have been having trouble finding sufficient information or connecting ...

What is the best way to deactivate div elements once an overlay has been applied to them?

My goal is to place an overlay on my form to prevent users from accessing the content. Even though I have added an overlay, users can still interact with input fields. How can I prevent that? .overlay { background: rgba(0, 0, 0, .75); text-align: ce ...

Align the h2 header vertically within a div container

So, here's the HTML structure that I'm working with: <div class="category"> <div class="container bottom"> <h2>Name1</h2> </div> <div class="container top"> <h2>Name2</h2&g ...

Trouble with closing windows in the in-app browser on Android devices

Is there a method to successfully close the in-app browser? Despite window.close working on iOS devices, it is not effective on Android. I have experimented with alternatives like window.top.close and window.open("", "_self") window.close, but none have ...

registration bootstrap form not functioning properly with ajax request

When the register function in a file named signup.php captures field values with Ajax and sends them to register.php, it should display a toast reply. // JavaScript code inside signup.php <script type="text/javascript"> function register(){ v ...

Encountering a "Parse error: syntax error, unexpected T_IF" while trying to use the return statement

I've encountered a parse error in some code I'm working on. When trying to create an if function outside of the $return variable and referencing it with a session, it works fine. However, I know this isn't considered "good" coding practice. ...

Annoying AngularJS Scrolling Problem

I am facing an issue with a Container that loads multiple views <md-content flex id="content"> <div ng-view></div> </md-content> One of the loaded views has the following structure: <div layout="column" id="selection-whit ...

Function is still undefined despite being included in the code

I've been working on a PHP script to export data from a database table to an Excel file. However, when trying to run the code, I encountered an error message: Fatal error: Call to undefined function buscarFaltantesPorProveedor() in /require/exportarFa ...

Is it possible to trigger the @click event in Vuejs when utilizing v-html to render HTML content?

Here is an interesting HTML scenario: errorText: '<a class="button" @click.prevent="enableExceedable(issue.mapping)">Enable exceedable limits</a>'; I am trying to insert this string into the following div: <div v-if="hasIssue != ...

tally up the elements within the array

I want to tally the occurrences of likes and unlikes in an array. $content is structured as either {"userid":"1","like":"1"} or {"userid":"1","unlike":"1"}. The goal is to calculate the number of like and unlike records in a table. Currently, the displ ...

Is it feasible to capture a screenshot of a URL by using html2canvas?

Is it possible to take a screenshot of a specific URL using html2canvas? For example, if I have the following URLs: mydomain.com/home mydomain.com/home?id=2 mydomain.com/home/2 How can I capture and display the screenshot image on another page? window ...

Using Twitter upload and update_with_media API in conjunction with curl

Looking to share a photo URL on Twitter? Check out the code snippet below: curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ci, CURLOP ...

Determine the minimum width in an HTML table's <td> tags

One issue I have encountered is with the columns in my table. I need each column to adjust its width dynamically based on the size of the browser window. However, I also want to ensure that the columns are not too small. To address this, I attempted to se ...

The ng-click functionality seems to be malfunctioning when used within the controller in conjunction with ng-bind

After coding, I noticed that my ng-click function is not working. When I inspected the element, I couldn't find ng-click displayed anywhere. Can someone please help me figure out what I'm doing wrong? var app = angular.module('myApp' ...

How come the styles in my CSS file aren't being applied to my images based on their class or ID?

When I apply a className or id to my img tag in my JavaScript (using React.js) and then add a style that references that id or class, the style does not get applied. However, when I do the same for a div, everything works perfectly fine. <--JavaScript- ...

Is there a way to determine which radio button has been chosen using jQuery?

I'm trying to retrieve the value of the selected radio button using jQuery. Can anyone help with this? Currently, I am able to target all radio buttons like so: $("form :radio") But how can I determine which one is actually selected? ...

Google Chrome has trouble displaying the body element at 100% height

Having an issue with Google Chrome – the body element is not reaching 100% height. In my website samples, at 100% zoom when hovering over a menu element (such as "O nás"), I change the background color of the body element. However, in Chrome, the botto ...

What benefits does React offer that jQuery does not already provide?

What sets ReactJS apart from jQuery? If jQuery can already handle everything, why should we use React? I've tried to research on Google but still don't have a clear answer. Most explanations focus on terms like "views," "components," and "state" ...