【问题标题】:How to create a HTML Table from a PHP array?如何从 PHP 数组创建 HTML 表?
【发布时间】:2011-06-12 09:03:31
【问题描述】:

如何从 PHP 数组创建 HTML 表格?标题为 'title''price''number' 的表格。

$shop = array(
    array("rose",   1.25, 15),
    array("daisy",  0.75, 25),
    array("orchid", 1.15, 7 ),
); 

【问题讨论】:

标签: php html arrays


【解决方案1】:

最好像这样将数据提取到数组中:

<?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) 
             ); 
?>

然后做这样的事情,即使您稍后在数据库中的表中添加更多列,它也应该可以正常工作。

<?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; ?>

【讨论】:

  • 智能表格创建方式。我根据您的代码创建了一个有用的函数。谢谢
  • array_map() 返回一个数组,并且 $row 不是通过引用传递的,因此该行基本上什么都不做,不是吗?
  • 有人能解释一下 array_map('htmlentities', $row) 吗?我不明白
  • @GalangRe htmlentities() 只是确保可以显示一个值并且不会破坏 HTML 代码。 array_map() 是一个 php 函数,用于将函数应用于数组的每个元素。所以结合起来,这将确保所有值都是 HTML 保存的。但是:我强烈建议您不要这样编码,这就是 PHP 于 1994 年开始的方式,与之协作绝对是丑陋、难以管理和地狱般的噩梦。不要混合 PHP 代码和输出。不要打开/关闭 PHP 解释器。
【解决方案2】:

这是我的:

<?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'=>'tom@example.org', 'company'=>'example ltd'),
    array('first'=>'hugh', 'last'=>'blogs', 'email'=>'hugh@example.org', 'company'=>'example ltd'),
    array('first'=>'steph', 'last'=>'brown', 'email'=>'steph@example.org', 'company'=>'example ltd')
);

echo build_table($array);
?>

【讨论】:

【解决方案3】:
   <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>

【讨论】:

  • 模板标签有什么问题? @HalfCrazed
  • 短标签并非在所有系统上都可用
【解决方案4】:

您也可以使用 array_reduce

array_reduce — 使用回调函数迭代地将数组缩减为单个值

示例:

$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>";

【讨论】:

  • 尽管这只是三行代码,但从某种意义上说,它是一种最简洁的解决方案,因为它使用适当的 PHP 结构来完成这项工作。
【解决方案5】:

这是最好、最简单和最有效的方法之一。 您可以将数组转换为具有任意数量的列或行的表。 它将数组键作为表头。不需要array_map。

function array_to_table($matriz) 
{   
   echo "<table>";

   // Table header
        foreach ($matriz[0] as $clave=>$fila) {
            echo "<th>".$clave."</th>";
        }

    // Table body
       foreach ($matriz as $fila) {
           echo "<tr>";
           foreach ($fila as $elemento) {
                 echo "<td>".$elemento."</td>";
           } 
          echo "</tr>";
       } 
   echo "</table>";}

【讨论】:

    【解决方案6】:
    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>';
    

    【讨论】:

      【解决方案7】:
      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>";
      

      【讨论】:

        【解决方案8】:

        构建两个 foreach 循环并遍历您的数组。 打印出该值并在其周围添加 HTML 表格标签。

        【讨论】:

          【解决方案9】:

          这是我的答案。

          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;
              }
          }
          

          但是,您的表头必须是数组的一部分,这在来自数据库时很常见。例如

          $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);
          

          希望对你有帮助;)

          【讨论】:

          • 你忘了用 htmlspecialchars 编码你的 str,所以数据应该被编码,除非你给它一个不编码的选项
          【解决方案10】:

          您可以使用此功能。要添加表头,您可以设置第二个参数$myTableArrayHeader,并对正文前面的表头信息执行相同操作:

          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;
          }
          

          【讨论】:

            【解决方案11】:

            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;``
            }
            

            【讨论】:

              【解决方案12】:
                  <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>
              

              【讨论】:

                【解决方案13】:
                <?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>';
                

                你可以优化它,但应该这样做。

                【讨论】:

                  【解决方案14】:

                  您可以使用 foreach 迭代数组 $shop 并在每次迭代时获取其中一个数组以回显其值,如下所示:

                  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>';
                  

                  【讨论】:

                    【解决方案15】:

                    这会将二维数组打印为表格。

                    第一行将是标题。

                    function array_to_table($table) 
                    {   
                        echo "<table>";
                    
                        // Table header
                        foreach ($table[0] as $header) {
                          echo "<th>".$header."</th>";
                        }
                    
                        // Table body
                        $body = array_slice( $table, 1, null, true);
                        foreach ($body as $row) {
                          echo "<tr>";
                            foreach ($row as $cell) {
                              echo "<td>".$cell."</td>";
                            } 
                          echo "</tr>";
                        }     
                      echo "</table>";
                    }
                    

                    用法:

                    arrayOfArrays = array(
                        array('header1',"header2","header3"),
                        array('1.1','1.2','1.3'),
                        array('2.1','2.2','2.3'),
                    );
                    
                    
                    array_to_table($arrayOfArrays);
                    

                    结果:

                    <table><tbody><tr><th>header1</th><th>header2</th><th>header3/th><tr><td>1.1</td><td>1.2</td><td>1.3</td></tr><tr><td>2.1</td><td>2.2</td><td>2.3</td></tr><tr><td>3.1</td><td>3.2</td><td>3.3</td></tr></tbody></table>
                    

                    【讨论】:

                      【解决方案16】:

                      数组到表中。 数组到 div。 JSON 到表中。 JSON 转换成 div。

                      所有人都很好地处理了这个类。 Click here to get a class

                      怎么用?

                      只需获取并反对

                      $obj = new Arrayinto();
                      

                      创建一个要转换的数组

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

                      如果你想将 Array 转换为 table。打电话给这个。

                      $result = $obj->process_table();
                      

                      如果你想将 Array 转换为 div。打电话给这个。

                      $result = $obj->process_div();
                      

                      假设你有一个 JSON

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

                      你可以像这样转换成table/div

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

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

                      【讨论】:

                        【解决方案17】:

                        我也有类似的需求,但我的数组可能包含key/valuekey/arrayarray of arrays,比如这个数组:

                        $array = array(
                            "ni" => "00000000000000",
                            "situacaoCadastral" => array(
                                "codigo" => 2,
                                "data" => "0000-00-00",
                                "motivo" => "",
                            ),
                            "naturezaJuridica" => array(
                                "codigo" => "0000",
                                "descricao" => "Lorem ipsum dolor sit amet, consectetur",
                            ),
                            "dataAbertura" => "0000-00-00",
                            "cnaePrincipal" => array(
                                "codigo" => "0000000",
                                "descricao" => "Lorem ips",
                            ),
                            "endereco" => array(
                                "tipoLogradouro" => "Lor",
                                "logradouro" => "Lorem i",
                                "numero" => "0000",
                                "complemento" => "",
                                "cep" => "00000000",
                                "bairro" => "Lorem ",
                                "municipio" => array(
                                    "codigo" => "0000",
                                    "descricao" => "Lorem ip",
                                ),
                            ),
                            "uf" => "MS",
                            "pais" => array(
                                "codigo" => "105",
                                "descricao" => "BRASIL",
                            ),
                            "municipioJurisdicao" => array(
                                "codigo" => "0000000",
                                "descricao" => "DOURADOS",
                            ),
                            "telefones" => array(
                                array(
                                    'ddd' => '67',
                                    'numero' => '00000000',
                                ),
                            ),
                            "correioEletronico" => "lorem@ipsum-dolor-sit.amet",
                            "capitalSocial" => 0,
                            "porte" => "00",
                            "situacaoEspecial" => "",
                            "dataSituacaoEspecial" => ""
                        );
                        

                        我创建的要解决的函数是:

                        function array_to_table($arr, $first=true, $sub_arr=false){
                            $width = ($sub_arr) ? 'width="100%"' : '' ;
                            $table = ($first) ? '<table align="center" '.$width.' bgcolor="#FFFFFF" border="1px solid">' : '';
                            $rows = array();
                            foreach ($arr as $key => $value):
                                $value_type = gettype($value);
                                switch ($value_type) {
                                    case 'string':
                                        $val = (in_array($value, array(""))) ? "&nbsp;" : $value;
                                        $rows[] = "<tr><td><strong>{$key}</strong></td><td>{$val}</td></tr>";
                                        break;
                                    case 'integer':
                                        $val = (in_array($value, array(""))) ? "&nbsp;" : $value;
                                        $rows[] = "<tr><td><strong>{$key}</strong></td><td>{$value}</td></tr>";
                                        break;
                                    case 'array':
                                        if (gettype($key) == "integer"):
                                            $rows[] = array_to_table($value, false);
                                        elseif(gettype($key) == "string"):
                                            $rows[] = "<tr><td><strong>{$key}</strong></td><td>".
                                                array_to_table($value, true, true) . "</td>";
                                        endif;
                                        break;
                                    default:
                                        # code...
                                        break;
                                }
                            endforeach;
                            $ROWS = implode("\n", $rows);
                            $table .= ($first) ? $ROWS . '</table>' : $ROWS;
                            return $table;
                        }
                        
                        echo array_to_table($array);
                        

                        输出是this

                        【讨论】:

                          【解决方案18】:

                          这是@GhostInTheSecureShell 答案的更通用版本。

                          <?php
                          function build_tabular_format($items)
                          {
                              $html = '';
                              $items_chunk_array = array_chunk($items, 4);
                              foreach ($items_chunk_array as $items_single_chunk)
                              {
                                  $html .= '<div class="flex-container">';
                                  foreach ($items_single_chunk as $item)
                                  {
                                      $html .= '<div class="column-3">';
                                      $html .= $item['fields']['id'];
                                      $html .= '</div>';
                                  }
                                  $html .= '</div>';
                              }
                              return $html;
                          }
                          
                          $items = array(
                              array(
                                  'fields' => array(
                                      'id' => '1',
                                  ) ,
                              ) ,
                              array(
                                  'fields' => array(
                                      'id' => '2',
                                  ) ,
                              ) ,
                              array(
                                  'fields' => array(
                                      'id' => '3',
                                  ) ,
                              ) ,
                              array(
                                  'fields' => array(
                                      'id' => '4',
                                  ) ,
                              ) ,
                          
                              array(
                                  'fields' => array(
                                      'id' => '5',
                                  ) ,
                              ) ,
                              array(
                                  'fields' => array(
                                      'id' => '6',
                                  ) ,
                              ) ,
                              array(
                                  'fields' => array(
                                      'id' => '7',
                                  ) ,
                              ) ,
                              array(
                                  'fields' => array(
                                      'id' => '8',
                                  ) ,
                              ) ,
                          );
                          
                          echo build_tabular_format($items);
                          ?>
                          

                          输出会是这样的:

                          <div class="flex-container">
                              <div class="column-3">1</div>
                              <div class="column-3">2</div>
                              <div class="column-3">3</div>
                              <div class="column-3">4</div>
                          </div>
                          <div class="flex-container">
                              <div class="column-3">5</div>
                              <div class="column-3">6</div>
                              <div class="column-3">7</div>
                              <div class="column-3">8</div>
                          </div>
                          

                          【讨论】:

                            猜你喜欢
                            • 1970-01-01
                            • 2012-11-23
                            • 1970-01-01
                            • 2015-06-16
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 2015-07-17
                            • 1970-01-01
                            相关资源
                            最近更新 更多