ASCII码 ASCII码

PHP--实例演示php模板语法及与html混编技巧

发布于:2022-04-21 15:03:44  栏目:技术文档

代码如下:

  1. <?php
  2. // 用二维数组来模拟数据表查询结果集
  3. $stus = [
  4. ['id' => 1, 'name' => '刘备', 'course' => 'js', 'score' => 83],
  5. ['id' => 2, 'name' => '关羽', 'course' => 'php', 'score' => 75],
  6. ['id' => 3, 'name' => '张飞', 'course' => 'js', 'score' => 52],
  7. ['id' => 4, 'name' => '孙权', 'course' => 'php', 'score' => 88],
  8. ['id' => 5, 'name' => '周瑜', 'course' => 'js', 'score' => 65],
  9. ['id' => 6, 'name' => '孔明', 'course' => 'php', 'score' => 53],
  10. ['id' => 7, 'name' => '赵云', 'course' => 'js', 'score' => 63],
  11. ['id' => 8, 'name' => '马超', 'course' => 'js', 'score' => 77],
  12. ['id' => 9, 'name' => '姜维', 'course' => 'php', 'score' => 93],
  13. ['id' => 10, 'name' => '黄忠', 'course' => 'js', 'score' => 81],
  14. ]
  15. ?>
  16. <!DOCTYPE html>
  17. <html lang="zh-CN">
  18. <head>
  19. <meta charset="UTF-8">
  20. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  21. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  22. <title>php流程控制的模板语法/替代语法</title>
  23. <style>
  24. table {
  25. border-collapse: collapse;
  26. width: 360px;
  27. text-align: center;
  28. }
  29. table th,
  30. table td {
  31. border: 1px solid #000;
  32. padding: 5px;
  33. }
  34. table caption {
  35. font-size: 1.3em;
  36. }
  37. table thead {
  38. background-color: lightcyan;
  39. }
  40. .active {
  41. color: red;
  42. }
  43. </style>
  44. </head>
  45. <body>
  46. <table>
  47. <caption>学生成绩表</caption>
  48. <thead>
  49. <tr>
  50. <th>ID</th>
  51. <th>姓名</th>
  52. <th>课程</th>
  53. <th>成绩</th>
  54. </tr>
  55. </thead>
  56. <tbody>
  57. <!-- php模板语法的目标: html与php代码分离 -->
  58. <?php foreach ($stus as $stu) : ?>
  59. <!-- "{" => 冒号加php结束标记 -->
  60. <!-- 当前已离开了php环境,处于html中 -->
  61. <!-- 使用短标签进行简化: 只打印一个变量 -->
  62. <!-- <tr>
  63. <td><?php echo $stu['id'] ?></td>
  64. <td><?php echo $stu['name'] ?></td>
  65. <td><?= $stu['course'] ?></td>
  66. <td><?= $stu['score'] ?></td>
  67. </tr> -->
  68. <!-- 只输出成绩大于70分 -->
  69. <!-- <?php if ($stu['score'] > 70) : ?>
  70. <tr>
  71. <td><?php echo $stu['id'] ?></td>
  72. <td><?php echo $stu['name'] ?></td>
  73. <td><?= $stu['course'] ?></td>
  74. <td class="active"><?= $stu['score'] ?></td>
  75. </tr>
  76. <?php endif ?> -->
  77. <!-- 输出全部,并将超过90分的成绩描红 -->
  78. <tr>
  79. <td><?php echo $stu['id'] ?></td>
  80. <td><?php echo $stu['name'] ?></td>
  81. <td><?= $stu['course'] ?></td>
  82. <?php $active = $stu['score'] > 90 ? "active" : '' ?>
  83. <td class=<?= $active ?>><?= $stu['score'] ?></td>
  84. </tr>
  85. <!-- 动态设置样式的方法 -->
  86. <?php endforeach ?>
  87. </tbody>
  88. </table>
  89. </body>
  90. </html>

运行后

相关推荐
阅读 +