欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

函数——生成表格

程序员文章站 2022-03-07 19:51:54
...

函数——生成表格

  • php代码:
  1. $arr = [
  2. [
  3. 'name' => '欧阳克',
  4. 'age' => '38岁',
  5. 'gongfu' => 'php基础',
  6. 'sex' => '男'
  7. ],
  8. [
  9. 'name' => '灭绝师太',
  10. 'age' => '18岁',
  11. 'gongfu' => 'uniapp',
  12. 'sex' => '女'
  13. ],
  14. [
  15. 'name' => '朱老师',
  16. 'age' => '48岁',
  17. 'gongfu' => 'html前端',
  18. 'sex' => '男'
  19. ],
  20. [
  21. 'name' => '西门大官人',
  22. 'age' => '28岁',
  23. 'gongfu' => '实战',
  24. 'sex' => '男'
  25. ],
  26. [
  27. 'name' => '裘千丈',
  28. 'age' => '48岁',
  29. 'gongfu' => '实战',
  30. 'sex' => '男'
  31. ]
  32. ];
  33. //列名及列宽, 不同的列宽度是不一样的
  34. $head = [
  35. ['姓名', 120],
  36. ['年龄',60],
  37. [ '功夫',200 ],
  38. ['性别',60]
  39. ];
  40. // 定义函数
  41. function table(array $arr,$head){
  42. $table = '<table border="1" cellspacing="0">';
  43. $table .='<caption style="color:#55a"><h3>教师功夫信息表</h3></caption>';
  44. // 表头设置背景色
  45. $table .= ' <thead style="background-color:#888;color:#fff">';
  46. $table .= ' <tr>';
  47. foreach($head as $head_k=>$head_v){
  48. $table .= ' <th width="'. $head_v[1] .'">'. $head_v[0] .'</th>';
  49. }
  50. $table .= ' </tr>';
  51. $table .= ' </thead>';
  52. $table .= ' <tbody>';
  53. foreach($arr as $k=>$v){
  54. //根据行号的奇偶设置背景色,形成斑马线
  55. if($k%2){
  56. $table .= ' <tr>';
  57. }else{
  58. $table .= ' <tr class="bgc">';
  59. }
  60. foreach($v as $kk=>$vv){
  61. $table .= ' <td style=" text-align: center">'. $vv .'</td>';
  62. }
  63. $table .= ' </tr>';
  64. }
  65. $table .= ' </tbody>';
  66. $table .= '</table>';
  67. return $table;
  68. }
  69. // 调用函数
  70. echo table($arr,$head);
  • CSS
  1. <style>
  2. .bgc{
  3. background: #ddd;
  4. }
  5. </style>