Here is my solution:
<table id="datatable-responsive" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<?php if (isset($subjectnames) && !empty($subjectnames)) { ?>
<tr>
<th>Name</th>
<?php $i = 1;
foreach ($subjectnames as $sub) {
?>
<th><?php echo $sub->subject. ' ['.$sub->exam_total_mark.']'; ?></th>
<?php } ?>
</tr>
</thead>
<tbody>
<?php
$x = 0;
foreach ($subjects as $obj) {
$i = 1;
if($x == count($subjectnames))
{ echo ' <tr>'; } ?>
<?php if($x == 0) { ?>
<td><?php echo $obj->studentname; ?></td> <?php } ?>
<?php foreach ($subjectnames as $sub) {
if($obj->subject == $sub->subject) {
$x++;
?>
<td><?php echo $obj->obtain_total_mark; ?></td>
<?php } }
if($x == count($subjectnames))
{
echo '</tr>';
$x=0;
}
?>
<?php $i++; } ?>
<?php }
else { ?>
<tr>
<td align="center"><?php echo $this->lang->line('no_data_found'); ?></td>
</tr>
<?php } ?>
</tbody>
</table>