Home > Mobile >  PHP Table Column name
PHP Table Column name

Time:02-26

I have an script for getting a table from a DB which is written in PHP.

I am trying to add name for each column to be in the first row:

A part of the Code is:

$rows = [];
foreach (range(1, 4) as $row) {
    $rows[$row] = "";
}
$rows["Name"] = $order->user->aFirstName;
$rows["Last Name"] = $alumn->aLastName;
$rows["Age"] = $alumn->aAge;
$rows["Gender"] = $alumn->aGender;
$string = "";
foreach ($rows as $r) {
    $string .= $r . "\t";
}

what I want to get is

1 | Name | Last Name | Age | Gender
2 | John | Des       | 45  | Male.

What I get now is the data in 1st row.

1 | John | Des       | 45  | Male.

Any suggestion? Thanks

CodePudding user response:

You can create a new first element in $rows using https://www.php.net/manual/de/function.array-unshift.php

$labels = ["Name" => "NameLabel", "Last Name" => "Last NameLabel" ...];
array_unshift($rows, $labels);

So the first element of the $rows array are the labels. Now when the table is generated is will display the labels at the top.

CodePudding user response:

You are loading the arrays incorrectly.

I assume you dont want to get the column names from the meta data available to you, and are happy to add the column names manually, if not let me know

$rows = [];
// add labels
$rows[] = ["Name", "Last Name", "Age", "Gender"];
#$rows[] = [$order->user->aFirstName, $alumn->aLastName, $alumn->aAge, $alumn->aGender];
// I dont have your data, so this is to simulate the above line
$rows[] = ['John', 'Des', 45, 'Male'];

$string = '';
foreach ($rows as $i => $row) {
    $n = $i 1;
    $string .= "$n\t";
    foreach ($row as $col){
        $string .= $col . "\t";
    }
    $string .= '<br>'. PHP_EOL;
}


print_r($string);

RESULTS, as you can see a Tab is not really enough to correctly format the table

1   Name    Last Name   Age Gender  <br>
2   John    Des 45  Male    <br>
  • Related