【问题标题】:How to convert multidimensional PHP array to html table如何将多维PHP数组转换为html表
【发布时间】:2019-09-22 17:32:31
【问题描述】:

我正在尝试从多维数组变量$array2 中创建一个 HTML 表,它是一个查询(来自 mysql 数据库 PHP 查询而不是自制查询),如下所示;

Array
(
    [0] => Array
        (
            [0] => M2TYEE
            [1] => Jean
            [2] => Harvey
            [3] => London
            [4] => 0314686334
        )

    [1] => Array
        (
            [0] => E26YBE
            [1] => Tom
            [2] => Cruise
            [3] => New York
            [4] => 0635625735     
        )

)

我想让表格看起来像这样



|ID     |FIRST NAME| LAST NAME |  CITY     | PHONE      |
________________________________________________________
|M2TYEE | Jean     |  Harvey   |  London   | 0314686334 |
--------------------------------------------------
|E26YBE | Tom      |  Cruise   |  New York | 0635625735 |

它们的数组可能会增加到最多 1000 个值,因此需要使用 while/for 循环。 任何帮助将不胜感激

【问题讨论】:

    标签: php html mysql arrays html-table


    【解决方案1】:

    您可以使用array_mergeforeach 获得所需的输出

    $arr = array_merge([ 0 => ['ID','FIRST NAME','LAST NAME','CITY','PHONE']],$arr);
    $html = '<table border="1">';
    foreach($arr as $row){
      $html .= '<tr>';
      foreach($row as $column){
        $html .= '<td>'.$column.'</td>';
      }
      $html .= '</tr>'; 
    }
    $html .= '</table>';
    echo $html;
    

    【讨论】:

    • 效果惊人的完美,但将第一行改为$arr = array_merge([ 0 =&gt; ['ID','FIRST NAME','LAST NAME','CITY','PHONE']],$array2);
    【解决方案2】:

    因为你的内部数组的大小是固定的(都有 4 个字段),你可以使用如下的单循环:

    echo "<table>";
    foreach($array2 as $index){
        echo "<tr>";
        echo "<td>".$index[0]."</td><td>".$index[1]."</td><td>".$index[2]."</td><td>".$index[3]."</td><td>".$index[4]."</td>";
        echo "</tr>";
    }
    echo "</table>";
    

    另一种方法:

    $result.="<table>";
    foreach($array2 as $index){
        $result.="<tr>";
        $result.="<td>".$index[0]."</td><td>".$index[1]."</td><td>".$index[2]."</td><td>".$index[3]."</td><td>".$index[4]."</td>";
        $result.="</tr>";
    }
    $result.="</table>";
    echo $resul;
    

    【讨论】:

    • 不太好用,但很有帮助。谢谢
    • @KalisploitTutorials,每个字段只能添加&lt;tr&gt;&lt;th&gt;Your Header title&lt;/th&gt;&lt;/tr&gt;
    猜你喜欢
    • 2020-02-28
    • 1970-01-01
    • 2020-02-06
    • 2018-03-31
    • 2014-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    相关资源
    最近更新 更多