Skip to content Skip to sidebar Skip to footer

Generate HTML Table Header From Multi Dimensional Array Dynamically

My requirement is to generate HTML table header with Dynamic multi dimensional array. e.g. Array will be like, $Array = ('Sr.No.'=>'', 'Subject'=>array('Maths','Sci','History

Solution 1:

Here you go:

$headers = "<thead>";
foreach ($Array as $key => $value)
{
    $headers .= "<th colspan='".max(sizeOf($Array[$key]),1)."'>".$key."</th>";
}
$headers .= "</thead>";

Here is a working DEMO

EDIT- BASED ON COMMENTS:
The demo above have the following code:

$Array = array("Sr.No." => "",'Subject'=>array('Maths','Sci','History','Social Sci'),  
              'Other Activities'=>array('Sports','Computer','Social'));

$table = "<table style='border-style: solid;'><thead>";
$headers = "<tr>";
$headers2 = $headers;
foreach ($Array as $key => $value)
{
  $headers .= "<th colspan='".max(sizeOf($Array[$key]),1)."' style='border-right: 1px solid;'>".$key."</th>";
 if(is_array($Array[$key]))
 {
     foreach ($Array[$key] as $key2 => $value2)
     {
         $headers2 .= "<th style='border: 1px dotted;'>".$value2."</th>";
     }
 }
 else{$headers2 .= "<th style='border:1px dotted;'></th>";}
}
$headers .= "</tr>";
$headers2 .= "</tr>";
$table .= $headers.$headers2."</thead></table>";

echo $table;  

Here are the results:

enter image description here


Post a Comment for "Generate HTML Table Header From Multi Dimensional Array Dynamically"