Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

johnw65's avatar

Display Data to Table format

I need to grab a query from different tables which have different number of columns to display and different column names. I like to out put into a Table format. Listed below is a sample query which has Title and Description as column name. The number of columns can vary. Since the column name (title and description) can be different for different queries, what is the best approach to display the data in a table format

Datasource:  
array:2 [▼
  0 => array:2 [▼
    "title" => "TITLE1"
    "description" => "DESCRIPTION1"
    
  ]
  1 => array:2 [▼
    "title" => "TITLE 2"
    "description" => "NEW DESCRIPTION"
   ]

Output into Table format:
title    |  description
___________________________
TITLE1 |  DESCRIPTION1
TITLE2|  NEW DESCRIPTION

0 likes
6 replies
Tray2's avatar

If I understand you correctly you should be able to use a union between the tables.

SELECT 'table1' AS soure', title  , description FROM table1
UNION ALL
SEELCT 'table2' AS source, title, description FROM table2
johnw65's avatar

@Tray2 , I should of been more clear, but I have the query working. But how can I view the data in a table format. Again, depending on the table, the column names are different. Do I need to put into an array in the controller? That way, I can output to a table using a two dimensional array? Thanks.

Tray2's avatar

@johnw65 you mean that you dynamically count the columns and assign the names to each column?

johnw65's avatar

@Tray2 , I'm trying display the data in this table format:

title    |  description
___________________________
TITLE1 |  DESCRIPTION1
TITLE2|  NEW DESCRIPTION

However, another query should be able to display regardless of the column name. So I guess my question is on the controller, how can I create an array from a query to create an array like below. That way, even though I don't know the column name, I can just display the data. My apologies for not being clear.

data[0][0], data[0][1]
data[1][0], data[1][1]
Column1, Column2, Column3
_______________________

firstdataColumn1 | firstdataColum2, firstdataColumn3
secondataColumn1| seconddataColumn2| seconddataColumn3
...

Tray2's avatar
Tray2
Best Answer
Level 73

@johnw65 I think you need to create some kind of helper function that converts the collection into columns and rows. Another option is to take a look at datatables.

https://datatables.net/

johnw65's avatar

@Tray2 , thanks for replying. I'm going to look at helper function that converts the collection. Appreciate your assistance. I'm very familiar datatable.

1 like

Please or to participate in this conversation.