我有一个名为categories
的控制器,我有
function description($id=null) {
$this->load->helper(array('form', 'url'));
$this->load->library('session');
$this->load->view('category/description');
$this->load->model('userdata_model');
$data = $this->userdata_model->desc($id);
$this->load->view('category/description', $data);
}
现在当我print_r($data);
时,它会给我以下结果
Array
(
[0] => stdClass Object
(
[id] => 4481
[title] => Dvd Recorder Post
[image_name] =>
[image_name_work] =>
[video_name] =>
[work_type] => tape-recrder
[description] => Test first..
[agency] =>
[services] =>
[photographer] =>
[company] =>
[director] =>
[dop] =>
[userid] =>
[display_order] => 99999
[latest_work] => No
[status] => Active
[post_adddate] => 2012-03-26 10:14:07
[date] => 2012-03-26 10:14:07
[sub_cat] => dvd-reorder
[views] => 75
[url] => Dvd-recorder-post
[post_cache] =>
[post_cat_id] => 0
[post_link] =>
[post_pubdate] =>
[post_seo_url] =>
[post_status] => 0
[post_type] => 0
)
)
现在,当我尝试在视图页面的$data
中访问description.php
时,它会出现以下错误
A PHP Error was encountered Severity: Notice Message: Undefined variable: data Filename: category/description.php Line Number: 2
有人知道为什么吗?
答案 0 :(得分:2)
CodeIgniter使用extract
在视图页面中生成变量。因此,您必须传入一个关联数组作为$this->load->view()
调用的第二个参数。在这种情况下,如果您希望将变量命名为data
,则必须传入一个元素键为data
的数组,该值是您从模型中检索的数据。 / p>
$data = array('data' => $this->userdata_model->desc($id));
$this->load->view('category/description', $data);
答案 1 :(得分:0)
你可以这样做
$data["ids"] = $this->userdata_model->desc($id);
$this->load->view('category/description', $data);
在您的视图中,您可以使用访问变量
$ids
答案 2 :(得分:0)
$data
是一个数组,包含您希望在视图页面上显示的所有信息。
在控制器中:
$this->load->model( 'userdata_model' );
// .. other code
$data = array(
'description' => $this->userdata_model->desc($id)
);
$this->load->view('category/description', $data );
在视图中:
<div><?php echo $description; ?></div>
答案 3 :(得分:0)
因为您在调用之前调用了View,所以删除该行,几乎是好的
$this->load->helper(array('form', 'url'));
$this->load->library('session');
$this->load->model('your model');
$data['Posts'] = $this->YourModel->ModelMethod();
$this->load->view('Your view', $data);
在您看来像这样的
<?php foreach($Posts as $item): ?>
<?= item['id'] ;?> Or if you have STD Class <?= item->id ;?>
<?php endforeach; ?>