在帖子Codeigniter result_array() returning one row https://stackoverflow.com/users/315828/xbonez回答是这样的
function getAllUsers()
{
$rows = array(); //will hold all results
$query = $this->db->get('users');
foreach($query->result_array() as $row)
{
$rows[] = $row; //add the fetched result to the result array;
}
return $rows; // returning rows, not row
}
在你的控制器中:
$data['users'] = $this->yourModel->getAllUsers();
$this->load->view('yourView',$data);
在你看来
//在您的视图中,$ users是一个数组 . 迭代它
<?php foreach($users as $user) : ?>
<p> Your first name is <?= $user['fName'] ?> </p>
<?php endforeach; ?>
从控制器启动查询并且查询结果在 $data['users']
中,但在视图中我们正在迭代 $users
. 这是为什么?
4 回答
在codeigniter(或者像cakePHP这样的mvc框架)中,我们在Controller中使用键和值构建数组 . 然后将其传递给视图作为变量 .
所以
$data['users']=array(key=>val)
将转到视图并作为echo $users['key']
进行访问 .仔细查看控制器中的所有变量键(例如
$data['users']
这里用户是关键)成为视图中的实际变量(例如$users
),这就是我们称之为MVC结构的原因 .如果您在控制器中设置,
在您的视图中,您将调用about参数
只需检查
system/core
中的loader.php
并找到"public function view"
,它就会回答您的问题 .$this->load->view()
功能accepts 2 arguments
,第二个是可选的 . 第一个参数是view without extension
的名称 . 第二个参数是array containing key value pairs
. 如果传递第二个参数然后all keys will be converted into variable names
并且它们将占用该数组中存在的值