Bien Thuy Bien Thuy - 7 months ago 52
SQL Question

PHP explode data and show in table

I have a problem when coding in PHP.

I have a data in mysql like this:

$data_room = '2010,2011|Math-9,Informatic-8,History-6,Moresingle-5,Other-8
2011,2012|Math-6,Informatic-7,History-5,Moresingle-3,Other-7';
echo '<table><tbody>';
$data = explode("\n", $data_room);
foreach($data as $row){
echo '<tr>';
$row = explode('|',$row);
echo '<td>';
foreach($row as $cell){
$row2 = explode(',',$cell);
echo $row2[0].'->'.$row2[0].'</td></tr><tr>';
foreach($row2 as $cell2){
echo '<td>';
echo $cell2;
echo '</td>';
}
echo '</tr>';
}
}
echo '</tbody></table>';


Now I want to show it in a table like this:

Table that I want to show

How can I do it?

Answer

I think first you need to create the table header using one for each.Then for each row another for each. Also you need to do nested for each and explode(). Please have a look on the below scripts. This may help you.

<?php
$data_room = '2010,2011|Math-9,Informatic-8,History-6,Moresingle-5,Other-8
2011,2012|Math-6,Informatic-7,History-5,Moresingle-3,Other-7
2012,2013|Math-65,Informatic-17,History-15,Moresingle-13,Other-17';
echo '<table border="1" ><tbody>';
$data = explode("\n", $data_room);
$header = explode('|',$data[0]);
$header_row = explode(',',$header[1]);
/*Table header*/

 echo "<tr>";
 echo "<td>&nbsp;</td>";
 foreach($header_row as $subject_mark)
 {
    $subject = explode('-',$subject_mark);
    echo "<td>".$subject[0]."</td>";

 }
 echo "</tr>";

 foreach($data as $row){
 $head_contents = explode('|',$row);

 /*Table contents*/
 echo "<tr>";
 echo "<td>".str_replace(',','-',$head_contents[0])."</td>";
 $subject_marks = explode(',',$head_contents[1]);
 foreach($subject_marks as $subject_mark)
 {
    $mark = explode('-',$subject_mark);
    echo "<td>".$mark[1]."</td>";

 }
 echo "</tr>";

}
echo '</tbody></table>';
?>
Comments