如何使用PHP使表标头具有动态值

时间:2018-11-01 07:56:18

标签: php html-table

我还需要使用PHP根据json array值附加动态表头。我在下面解释我的代码。

<?php
$resultArr=array(array("header"=>"Firstname","data"=>array("Jack","Ram")),array("header"=>"Lastname","data"=>array("Nayak","Das")),array("header"=>"Age","data"=>array("50","30")));
?>
<!doctype html>
<html>
<head>
<title>Demo Preview</title>
<meta name="robots" content="noindex, nofollow"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<style>
table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}
</style> 
</head>
<body>
<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Age</th>
  </tr>
  <tr>
    <td>Jack</td>
    <td>Nayak</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Ram</td>
    <td>Das</td>
    <td>30</td>
  </tr>
</table>
</body>
</html>

这里,我在表格中有静态值。我需要使用PHP根据数组(i.e-$resultArr)动态添加相同的值。

1 个答案:

答案 0 :(得分:1)

<?php
$resultArr=array(array("header"=>"Firstname","data"=>array("Jack","Ram")),array("header"=>"Lastname","data"=>array("Nayak","Das")),array("header"=>"Age","data"=>array("50","30")));

$nbPerson = count($resultArr[0]['data']);

?>
<!doctype html>
<html>
<head>
<title>Demo Preview</title>
<meta name="robots" content="noindex, nofollow"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<style>
table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}
</style> 
</head>
<body>
<table style="width:100%">
  <tr>
    <?php
        foreach($resultArr as $key => $array)
        {
            echo '<th>'.$array['header'].'</th>';
        }
    ?>
  </tr>
    <?php
        $i = 0;
        while($i < $nbPerson)
        {
            echo '<tr>';
            foreach($resultArr as $key => $array)
            {
                echo '<td>'.$array['data'][$i].'</td>';
            }
            echo '</tr>';
            $i++;
        }
    ?>
</table>
</body>
</html>

要对其进行测试:https://3v4l.org/NrQcI