How to create html table from associated array using php with for loop?

My associated array is as follows:

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

     ?>

expected output, as indicated in table format, using for loop:

<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

Any help would be appreciated. Thank.

+4
source share
4 answers

Use foreach()on two levels: one for the name and the other for labels with table tags as a string embedded in the php loop foreach().

Example:

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

Tested and working. As you might expect: use foreachinside 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>';
+1
source

Try the following:

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

    }
}
0
source

use foreach as

<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>";
  }
0
source

Source: https://habr.com/ru/post/1677143/


All Articles