PHP数组转HTML表格核心逻辑
复制以下代码以查看完整实现:
占位符用于插入标题文本:%s";初始化单元格字符串变量为空:$celdas="";
获取当前对象中数组元素的总数:$n=count($this->arr);
使用循环遍历数组中的每一行数据:for($i=0;$i<$n;$i++)
{
使用sprintf函数格式化表格行的开始标签,并应用背景色:$celdas.=sprintf("
占位符用于插入单元格文本:%s";}
返回最终生成的HTML表格字符串:return sprintf("
拼接额外的HTML属性、表头内容以及单元格内容到表格结构中:",$this->sextra,$titulos,$celdas);
}
定义一个示例方法用于演示功能:public function example()
{
定义包含列标题的数组:$tit=array("Apellidos","Nombre","Telefono");
定义第一行数据:$r1=array("Garcia","Ivan","888");
定义第二行数据:$r2=array("Marco","Alfonso","555");
实例化表格类:$x=new xtable();
调用方法设置表格标题数组:$x->titles($tit); //take titles array
一次性添加多行数据:$x->addrows(array($r1,$r2)); // take all rows at same time
生成并返回HTML代码以便展示或保存:return $x->html(); //return html code to get/show/save it
}
}
// 示例 $t1=new xtable(); echo $t1->example()."
";
$t2=new xtable(); for($i=1;$i<=10;$i+=2) { $t2->addrow(array("ODD",$i)); $t2->addrow(array("EVEN",$i+1)); } $t2->background(array("pink","gold")); $t2->titles(array("TYPE","#")); $t2->extra(" style='width:500px; background-color:cyan; color:navy;'"); echo $t2->html()."
";
$t3=new xtable(); for($i=1;$i<=6;$i++) { $t3->addrow(array("5x".$i,5*$i)); } $t3->background(array("olive","maroon")); $t3->titles(array("Multiplication table","5")); $t3->extra("style='border:dotted red 10px; padding-left:4px;padding-right:4px; text-align:right;width:500px; background-color:black; color:white;'"); echo $t3->html()."
";
$t4=new xtable(); $a=array("#"); for($i=1;$i<=10;$i++) { $a[]=$i; } $t4->addrow($a); $t4->background(array("pink","gold")); $tit=array(); $tit[]="Numbers"; for($i=1;$i<=10;$i++) $tit[]="#"; $t4->titles($tit); $t4->extra("style='border:solid 1px silver; padding-left:4px;padding-right:4px; text-align:center;width:500px; background-color:cyan; color:navy;'"); echo $t4->html()."
";
?>