CI框架传递数组到视图View层
function index() { $data['mytitle'] = "A website monitoring tool"; $data['mytext'] = "This website helps you to keep track of the other websites you control."; $this->load->view('basic_view',$data);}
?
我们把$data数组作为$this->load->view()的第二个叁数,在视图名称之后。视图接收到$data数组后,使用PHP函 数extract()把数组中的每个元素转换成内存变量,数组的键名即为变量名,值为变量内所包含的值。这些变量的值能直接被视图引用:
<html><head></head><body> <h1 class='test'><?php echo $mytitle; ?></h1> <p class='test'><?php echo $mytext; ?></p></body></html>
虽然你只能传送一个变量到视图, 但是通过建立数组,你能把大量变量整洁地传入视图。它似乎复杂, 但是实际上是一种紧凑和优秀的信息传输方式。
如果传递过来的数组是包含多个数据,那么就需要遍历,操作一般如下。先是控制器:
$data["notice"] =array('aaa','bbb'); $this->load->view('api/notice',$data);
?
视图中解析
<?phpif(count($notice)>0){ foreach($notice as $key =>$value ){?> <a href="#"><?php echo $value?></a><?php }?>
?再说下二维数组的传递与遍历问题。下面的程序实现遍历某个目录下的文件
?
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');class Data extends CI_Controller {public function index(){$this->load->helper('url');$data['page_title'] = '简明现代魔法';$data['pre_url'] = 'application/views/default/'; $this->load->view('default/header', $data); $this->load->view('default/index', $data); $this->load->view('default/footer');//$this->load->view('index');}public function gdnews(){$this->load->helper('url');$arr = array();function tree($directory) { $mydir = dir($directory); while($file = $mydir->read()){ // 是目录的话if((is_dir("$directory/$file")) AND ($file!=".") AND ($file!="..")) {//echo "<li><font color="#ff00cc"><b>$file</b></font></li>\n"; //tree("$directory/$file"); } // 不是目录else {$arr['name'][] = @iconv('GB2312','UTF-8',$file);$arr['time'][] = @iconv('GB2312','UTF-8',date('Y-m-d H:i:s', filemtime($file)));}}$mydir->close(); return $arr;}$dir = "datas/gdnews/";$arr = tree($dir);$data['files'] = $arr;$data['page_title'] = '简明现代魔法' ;$data['dir'] = $dir;$this->load->view('default/header', $data); $this->load->view('default/data', $data); $this->load->view('default/footer');}}?>
?
在视图中这么输出就可以:
?
<?php if(count($files)>0){ foreach($files['name'] as $key =>$value ){?> <p target="_blank">查看</a> <a href="#">删除</a></span></p><?php}}?>
?
?
?
?