在控制器中查询的数组数据,如何在模板中遍历出来?
1.控制器中查询数据库中的数据
<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
public function index(){
$user = M("user");
$data = $user->select();
$this->assign("users",$data);
$this->display();
}
}
2.在模板中可以通过 <volist>或<foreach>标签遍历数组
<!DOCTYPE html>
<html>
<head>
<meta charset="utf8">
<title>首页模板</title>
</head>
<body>
<volist name="users" id="user" offset="2" length="2" empty="没有信息">
{$user.id}--{$user.username}--{$user.password}--{$user.email}<br>
</volist>
<hr>
<foreach name="users" item="user">
{$user.id}--{$user.username}--{$user.password}--{$user.email}<br>
</foreach>
</body>
</html>
注意:<volist>标签中的 offset 是偏移量,后面的数值必须带引号 "",length是要遍历的条数,empty是表示在没有数据显示
同时,一般不建议通过offset和length限制遍历的数据,应该在控制器中直接通过where()方法限制查询的数据。可以减轻服务器的压力。
