如何使用php for for循环从关联数组创建html表?

时间:2017-05-15 06:27:23

标签: php mysql

我的关联数组如下:

   <?php
     $marks = array( 
        "mohammad" => array (
           "physics" => 35,
           "maths" => 30,   
           "chemistry" => 39
        ),

        "qadir" => array (
           "physics" => 30,
           "maths" => 32,
           "chemistry" => 29
        ),

        "zara" => array (
           "physics" => 31,
           "maths" => 22,
           "chemistry" => 39
        )
     );      

     ?>

使用for循环的表格式预期输出如下:

<table border="1">
        <tr><td>Name </td><td>  physics</td><td> maths </td><td>chemistry</td></tr>
     <tr><td>mohammad</td><td>  35    </td><td>   30</td><td>        39</td></tr>
     <tr><td>qadir   </td><td>   30 </td><td>     32</td><td>        29</td></tr>
          <tr><td>zara   </td><td>   31   </td><td>   22     </td><td>    39</td></tr>
</table>

enter image description here

任何帮助将不胜感激。感谢。

4 个答案:

答案 0 :(得分:3)

在两个级别上使用foreach(),一个用于名称,另一个用于带有表格标记的标记作为嵌入了php foreach()循环的字符串。

例如:

foreach($marks as $name => $mark)
{
    echo "<tr><td>".$name."</td>";
    foreach($mark as $key => $value)
    {
        echo "<td>".$value."</td>";
    }
    echo "</tr>";
}

答案 1 :(得分:1)

经过测试,它的工作原理您如何期待:在foreach内使用foreach

echo ' <table border=1 width=auto> <thead> <tr> <th>Name</th><th>physics</th><th>maths</th><th>chemistry</th‌​> </tr> </thead>';
echo '<tbody>  ';
foreach($marks as $key => $value)
{
   echo "<tr> <td>".$key."</td>";
   foreach($value as $strin)
   {
       echo '<td>'.$strin.'</td>';
   }
   echo '</tr> ';
  }
  echo '</tbody> </table>';

答案 2 :(得分:0)

试试这个:

foreach ($marks as $key => $value) {
 echo $key;
      foreach ($marks as $key => $value) {
       echo $value;

    }
}

答案 3 :(得分:0)

使用类似

的foreach
<th>
  <td>Name</td>
 <td>Physics</td>
 <td>math</td>
 <td>chemistry</td>
foreach($data as $array)
{
   echo "<tr><td>".$array['name']."</td>
           <td>".$array['physics']".</td>
         <td>".$array['math']".</td>
         <td>".$array['chemistry']".</td>
     </tr>";
  }