Skip to content
Advertisement

PHP table rows based on table header

i want to create a table of all classes as table header and rows with name of student in each class each column according to it header, all data come from two (students, classes) mx code :

<table>
    <thead >
<?php 
     foreach ($groupList as $group):
?>
      
     <th><?= $group['group_name'] ?></th>
<?php endforeach; ?>
</thead>
<tbody>
     <tr>
     <?php 
          foreach ($groupList as $group) {
              echo '<td>' ;
              foreach ($db->getStudentsByGroup($group['u_id']) as $name){
                 echo  $name['fname'] ;
              }
              echo '</td>';
          }
     ?>
        </tr>
</tbody>

this code shows them grouped as wanted but all names are in the same row as below

group1            group2
tom, sam, bob,    x, y ,...
mark, ...

, i tried to change the location of the (td, tr) but no success, any idea how to do it properly , thanks in advance

Advertisement

Answer

If i m not wrong this should do the trick!

my array:

$array = array(
    'group1' => array(
        'aaa',
        'bbb',
        'ccc'
    ),
    'group2' => array(
        'ddd',
        'eee',
        'fff'
    )   
);

Working code:

echo '
<table border="1">
    <thead>';
        
        foreach($array AS $tname => $tvalue){
            echo '<th>'.$tname.'</th>';
        }

    echo '
    </thead>
    <tbody>';

        $keys = array_keys($array);
        $first_key = $keys[0];
        foreach ($array[$first_key] as $id => $value) {
            $body .= "<tr>";
            foreach ($keys as $k) {
                $body .= "<td>" . $array[$k][$id] . "</td>";
            }
            $body .= "</tr>";
        }
        echo $body;

    echo '
    </tbody>
</table>';
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement