Create table from an array by making the keys the header

Asked

Viewed 28 times

1

Hello. In the system I am developing I have the possibility to create filters for queries, but queries do not always have as a result the same columns. The result is stored in a key-value array, where the key is the name of each BD column.

Example of query result:

Array
(
    [0] => Array
        (
            [indicador] => Precipitação total
            [fonte_de_dados] => INMET
            [microrregiao] => Campanha Meridional
            [sigla_uf] => RS
            [mes_coleta] => 1/2020
            [valor] => 0.140
            [unidade] => mm
        )

    [1] => Array
        (
            [indicador] => Precipitação total
            [fonte_de_dados] => INMET
            [microrregiao] => Caxias do Sul
            [sigla_uf] => RS
            [mes_coleta] => 1/2020
            [valor] => 0.194
            [unidade] => mm
        )

)

With this in mind, to avoid several "if...else", I intend to display at first in a table the name of each key (indicator, data fonte_de_data,...) as a table header and the values in the cells, as in the example below.

Exemplo de tabela

How can I make table header with keys? Mine foreach is as follows:

<table class="table table-hover table-striped">
   <?php
      foreach ($registros as $chave => $registro) {
         echo "<tr>";
         foreach ($registros[$chave] as $celula) {
             echo "<td>" . $celula . "</td>";
         }
         echo "</tr>";
      }
   ?>
</table>
  • If you make a foreach($array as $key => $value and print each '<td>'. $key .'</td>', n resolves?

  • The value is called by the key: $celula['indicador'];, and an array of keys can be via array_keys($celula);

1 answer

2

Basically you would need to check that $records is not empty and retrieve the keys from the first $records item. Here is an example.

Array Keys - https://www.php.net/manual/en/function.array-keys.php

Alternative syntax (if and foreach) - https://www.php.net/manual/en/control-structures.alternative-syntax.php

<?php

$registros = [
        [
        'indicador' => 'Precipitação total',
        'fonte_de_dados' => 'INMET',
        'microrregiao' => 'Campanha Meridional',
        'sigla_uf' => 'RS',
        'mes_coleta' => '1/2020',
        'valor' => '0.140',
        'unidade' => 'mm',
    ],
    [
        'indicador' => 'Precipitação total',
        'fonte_de_dados' => 'INMET',
        'microrregiao' => 'Caxias do Sul',
        'sigla_uf' => 'RS',
        'mes_coleta' => '1/2020',
        'valor' => '0.194',
        'unidade' => 'mm',
    ]
];
?>


<?php

    if (!empty($registros)):
?>
    <table class="table table-hover table-striped">
        <thead>
            <tr>
                <?php
                foreach (array_keys($registros[0]) as $cabecalho):
                    echo "<th>{$cabecalho}</th>";
                endforeach;
                ?>
            </tr>
        </thead>

        <tbody>

<?php

        foreach ($registros as $chave => $registro):

            echo "<tr>";

            foreach ($registros[$chave] as $celula):
                echo "<td>" . $celula . "</td>";
            endforeach;

            echo "</tr>";

        endforeach;
        
    else:
        echo "SEM RESULTADOS";
    endif;
?>

    <tbody>
</table>
  • It worked perfectly. Thank you, Marcos.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.