我们的数据未必都是存储在数据库中,很多时候是用数组来组织的。所以获取数组数据,进行分页是比较常见的编程要求。
在YII中我们可以利用CArrayDataProvider,可以对一个数组里面的数据进行分页
php代码如下
public function actionPage(){ $rawData = array( array('id'=>1,'username'=>'aa','password'=>'aaaaaa'), array('id'=>2,'username'=>'bb','password'=>'aaaaaa'), array('id'=>3,'username'=>'cc','password'=>'aaaaaa'), array('id'=>4,'username'=>'dd','password'=>'aaaaaa'), array('id'=>5,'username'=>'ee','password'=>'aaaaaa'), array('id'=>6,'username'=>'ff','password'=>'aaaaaa'), array('id'=>7,'username'=>'gg','password'=>'aaaaaa'), array('id'=>8,'username'=>'hh','password'=>'aaaaaa'), array('id'=>9,'username'=>'jj','password'=>'aaaaaa'), array('id'=>10,'username'=>'qq','password'=>'aaaaaa'), array('id'=>11,'username'=>'www','password'=>'aaaaaa'), array('id'=>12,'username'=>'xx','password'=>'aaaaaa'), array('id'=>13,'username'=>'zz','password'=>'aaaaaa'), ); $dataProvider=new CArrayDataProvider($rawData, array( 'id'=>'user', 'sort'=>array( 'attributes'=>array( 'id', 'username', 'password', ), ), 'pagination'=>array( 'pageSize'=>10, ), )); $this->render('page',array('dataProvider'=>$dataProvider)); }
在页面展示的时候使用CGridView进行数据显示
$this->widget('zii.widgets.grid.CGridView',array( 'id'=>'effectivepolicy-grid', 'dataProvider'=>$dataProvider, 'emptyText'=>'没有找到数据.', 'nullDisplay'=>'-', 'columns'=>array( array( 'name'=>'用户名', 'value'=>'$data["username"]', 'htmlOptions'=>array('style'=>'width:55px;') ), array( 'name'=>'密码', 'value'=>'$data["password"]', 'htmlOptions'=>array('style'=>'width:55px;') ), ), ));