CodeIgniter 採用 MVC 架構,控制器將資料陣列傳遞給視圖,視圖中使用 PHP 原生 foreach 迴圈輸出資料。
<?php
class SimpleController extends CI_Controller {
public function index() {
$data['my_list'] = ["do this", "clean up", "do that"];
$this->load->view('index', $data);
}
}
?>
index.php<html>
<head><title>Display Array Data</title></head>
<body>
<h1>Display Array Data</h1>
<?php foreach ($my_list as $item): ?>
<p><?php echo $item; ?></p>
<?php endforeach; ?>
</body>
</html>
<?php
// Controller
$data['users'] = [
['name' => 'Alice', 'email' => 'alice@example.com'],
['name' => 'Bob', 'email' => 'bob@example.com'],
];
$this->load->view('users', $data);
<!-- View users.php -->
<table border="1">
<tr><th>Name</th><th>Email</th></tr>
<?php foreach ($users as $user): ?>
<tr>
<td><?php echo $user['name']; ?></td>
<td><?php echo $user['email']; ?></td>
</tr>
<?php endforeach; ?>
</table>
alt syntax(foreach ... endforeach;)提升 HTML 可讀性。htmlspecialchars() 或 CI html_escape())防止 XSS。