Search code examples
phprow

PHP Table Column name


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


Solution

  • 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>