Como criar uma tabela HTML a partir de um array PHP?

Como faço para criar uma tabela HTML a partir de um array PHP? Um quadro com o Título "', 'Preço' , e 'Número' .

$shop = array(
    array("rose",   1.25, 15),
    array("daisy",  0.75, 25),
    array("orchid", 1.15, 7 ),
); 
Author: hakre, 2011-01-20

15 answers

Seria melhor ir buscar os dados para o array assim:

<?php
$shop = array( array("title"=>"rose", "price"=>1.25 , "number"=>15),
               array("title"=>"daisy", "price"=>0.75 , "number"=>25),
               array("title"=>"orchid", "price"=>1.15 , "number"=>7) 
             ); 
?>

E depois fazer algo assim, que deve funcionar bem mesmo quando você adicionar mais colunas à sua tabela na base de dados mais tarde.

<?php if (count($shop) > 0): ?>
<table>
  <thead>
    <tr>
      <th><?php echo implode('</th><th>', array_keys(current($shop))); ?></th>
    </tr>
  </thead>
  <tbody>
<?php foreach ($shop as $row): array_map('htmlentities', $row); ?>
    <tr>
      <td><?php echo implode('</td><td>', $row); ?></td>
    </tr>
<?php endforeach; ?>
  </tbody>
</table>
<?php endif; ?>
 63
Author: Richard Knop, 2015-04-06 21:21:04
Aqui está o meu.
<?php
    function build_table($array){
    // start table
    $html = '<table>';
    // header row
    $html .= '<tr>';
    foreach($array[0] as $key=>$value){
            $html .= '<th>' . htmlspecialchars($key) . '</th>';
        }
    $html .= '</tr>';

    // data rows
    foreach( $array as $key=>$value){
        $html .= '<tr>';
        foreach($value as $key2=>$value2){
            $html .= '<td>' . htmlspecialchars($value2) . '</td>';
        }
        $html .= '</tr>';
    }

    // finish table and return it

    $html .= '</table>';
    return $html;
}

$array = array(
    array('first'=>'tom', 'last'=>'smith', 'email'=>'[email protected]', 'company'=>'example ltd'),
    array('first'=>'hugh', 'last'=>'blogs', 'email'=>'[email protected]', 'company'=>'example ltd'),
    array('first'=>'steph', 'last'=>'brown', 'email'=>'[email protected]', 'company'=>'example ltd')
);

echo build_table($array);
?>
 29
Author: GhostInTheSecureShell, 2017-03-28 16:47:33
   <table>
     <tr>
       <td>title</td>
       <td>price</td>
       <td>number</td>
     </tr>
     <? foreach ($shop as $row) : ?>
     <tr>
       <td><? echo $row[0]; ?></td>
       <td><? echo $row[1]; ?></td>
       <td><? echo $row[2]; ?></td>
     </tr>
     <? endforeach; ?>
   </table>
 12
Author: bassneck, 2011-01-20 10:47:55
echo "<table><tr><th>Title</th><th>Price</th><th>Number</th></tr>";
foreach($shop as $v){
    echo "<tr>";
    foreach($v as $vv){
        echo "<td>{$vv}</td>";
    }
    echo "<tr>";
}
echo "</table>";
 4
Author: Mike Valstar, 2011-01-20 18:15:56

Você também pode usar ainda array_ reduce

Exemplo:

$tbody = array_reduce($rows, function($a, $b){return $a.="<tr><td>".implode("</td><td>",$b)."</td></tr>";});
$thead = "<tr><th>" . implode("</th><th>", array_keys($rows[0])) . "</th></tr>";

echo "<table>\n$thead\n$tbody\n</table>";
 3
Author: Dmitriy, 2016-06-09 13:18:19
Construa dois loops de cada vez e itere através da sua matriz. Imprime o valor e adiciona as marcas da tabela HTML em torno disso.
 2
Author: Tobias, 2011-01-20 10:42:59
echo '<table><tr><th>Title</th><th>Price</th><th>Number</th></tr>';
foreach($shop as $id => $item) {
    echo '<tr><td>'.$item[0].'</td><td>'.$item[1].'</td><td>'.$item[2].'</td></tr>';
}
echo '</table>';
 2
Author: Angelo R., 2011-01-20 18:13:30
    <table>
      <thead>
        <tr><th>title</th><th>price><th>number</th></tr>
      </thead>
      <tbody>
<?php
  foreach ($shop as $row) {
    echo '<tr>';
    foreach ($row as $item) {
      echo "<td>{$item}</td>";
    }
    echo '</tr>';
  }
?>
      </tbody>
    </table>
 1
Author: Sam Dufel, 2011-01-20 18:14:31

Pode usar esta função. Para adicionar o cabeçalho da tabela, poderá configurar um segundo parâmetro $myTableArrayHeader e fazer o mesmo com a informação do cabeçalho à frente do corpo:

function insertTable($myTableArrayBody) {
    $x = 0;
    $y = 0;
    $seTableStr = '<table><tbody>';
    while (isset($myTableArrayBody[$y][$x])) {
        $seTableStr .= '<tr>';
        while (isset($myTableArrayBody[$y][$x])) {
            $seTableStr .= '<td>' . $myTableArrayBody[$y][$x] . '</td>';
            $x++;
        }
        $seTableStr .= '</tr>';
        $x = 0;
        $y++;
    }
    $seTableStr .= '</tbody></table>';
    return $seTableStr;
}
 1
Author: dirkwinkhaus, 2017-03-28 22:09:37

Código PHP:

$multiarray = array (

    array("name"=>"Argishti", "surname"=>"Yeghiazaryan"),
    array("name"=>"Armen", "surname"=>"Mkhitaryan"),
    array("name"=>"Arshak", "surname"=>"Aghabekyan"),

);

$count = 0;

foreach ($multiarray as $arrays){
    $count++;
    echo "<table>" ;               

    echo "<span>table $count</span>";
    echo "<tr>";
    foreach ($arrays as $names => $surnames){

        echo "<th>$names</th>";
        echo "<td>$surnames</td>";

    }
    echo "</tr>";
    echo "</table>";
}

CSS:

table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;``
}
 1
Author: Argishti Yeghiazaryan, 2017-03-28 22:14:05
<?php

echo "<table>
<tr>
<th>title</th>
<th>price</th>
<th>number</th>
</tr>";
for ($i=0; $i<count($shop, 0); $i++)
{
    echo '<tr>';
    for ($j=0; $j<3; $j++)
    {
        echo '<td>'.$shop[$i][$j].'</td>';
    }
    echo '</tr>';
}
echo '</table>';
Podes optimizá-lo, mas deve servir.
 0
Author: zozo, 2011-12-15 01:04:52
Eis a minha resposta.
function array2Html($array, $table = true)
{
    $out = '';
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            if (!isset($tableHeader)) {
                $tableHeader =
                    '<th>' .
                    implode('</th><th>', array_keys($value)) .
                    '</th>';
            }
            array_keys($value);
            $out .= '<tr>';
            $out .= array2Html($value, false);
            $out .= '</tr>';
        } else {
            $out .= "<td>$value</td>";
        }
    }

    if ($table) {
        return '<table>' . $tableHeader . $out . '</table>';
    } else {
        return $out;
    }
}
No entanto, os cabeçalhos da sua mesa têm de fazer parte da matriz, o que é bastante comum quando vem de uma base de dados. por exemplo
$shop = array(
    array(
        'title' => 'rose',
        'price' => 1.25,
        'number' => 15,
    ),
    array(
        'title' => 'daisy',
        'price' => 0.75,
        'number' => 25,
    ),
    array(
        'title' => 'orchid',
        'price' => 1.15,
        'number' => 7,
    ),
);

print arrayToHtml($shop);
([3]}espero que ajude;)
 0
Author: frenus, 2013-10-02 10:40:11

Matriz na tabela. Matriz em div. JSON na mesa. JSON para div.

Estão todos a lidar bem com esta aula. Clique aqui para obter uma aula Como usá-lo?

Apenas pega e objecta {[[9]}

$obj = new Arrayinto();

Crie um array que queira converter

$obj->array_object = array("AAA" => "1111",
                  "BBB" => "2222",
                  "CCC" => array("CCC-1" => "123",
                                 "CCC-2" => array("CCC-2222-A" => "CA2",
                                                  "CCC-2222=B" => "CB2"
                                                 )
                                )

                 );

Se quiser converter o Array na tabela. Chamar.

$result = $obj->process_table();

Se quiser converter Array em div. Chamar.

$result = $obj->process_div();

Suponha se tem um JSON {[[9]}

$obj->json_string = '{
            "AAA":"11111",
            "BBB":"22222",
            "CCC":[
                    {
                        "CCC-1":"123"
                    },
                    {
                        "CCC-2":"456"
                    }
                  ] 
         }
        ';

Podes converter-te em quadro / div como este

$result = $obj->process_json('div');

Ou

$result = $obj->process_json('table');
Espero que isto te ajude.
 0
Author: Delickate, 2017-11-02 05:38:07

Pode usar foreach para iterar a matriz {[[2]} e obter uma das matrizes com cada iteração para ecoar os seus valores assim:

echo '<table>';
echo '<thead><tr><th>title</td><td>price</td><td>number</td></tr></thead>';
foreach ($shop as $item) {
    echo '<tr>';
    echo '<td>'.$item[0].'</td>';
    echo '<td>'.$item[1].'</td>';
    echo '<td>'.$item[2].'</td>';
    echo '</tr>';
}
echo '</table>';
 0
Author: Gumbo, 2018-03-16 15:04:31
<table id="usuarios">
        <tbody>
           <tr>
              <th>Nombre</th>
              <th>Apellido</th>
              <th>Email</th>
              <th>Institución educativa</th>
              <th>Fecha Registro</th>
           </tr>
           <?php
           if ($result->num_rows > 0) {// output data of each row
            while($row = $result->fetch_assoc()) {
                echo "<tr><td>".$row["Nombre"]."</td>";
                echo "<td>".$row["Apellido"]."</td>";
                echo "<td>".$row["Email"]."</td>";
                echo "<td>".$row["NombreInsEdu"]."</td>";
                echo "<td>".$row["FechaRegistro"]."</td></tr>";
             }
             } else {
                 echo "0 results";
                 }
                 $conn->close();
           ?>
        </tbody>
     </table>
 -1
Author: Alejandro Uranga Reyes, 2016-03-13 06:14:11