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 ($Arrayas$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 ($Arrayas$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:
Post a Comment for "Generate Html Table Header From Multi Dimensional Array Dynamically"