[英]Codeigniter Set variable
我有一個控制器命名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
)
)
現在,當我嘗試在視圖頁面中訪問description.php
中的$data
,它會出現以下錯誤
A PHP Error was encountered Severity: Notice Message: Undefined variable: data Filename: category/description.php Line Number: 2
有誰知道為什么?
CodeIgniter使用extract
在視圖頁面中生成變量。 因此,您必須傳入一個關聯數組作為$this->load->view()
調用的第二個參數。 在這種情況下,如果您希望將變量命名為data
,則必須傳入一個數組,其中元素鍵是data
,值是從模型中檢索的數據。
$data = array('data' => $this->userdata_model->desc($id));
$this->load->view('category/description', $data);
你可以這樣做
$data["ids"] = $this->userdata_model->desc($id);
$this->load->view('category/description', $data);
在您的視圖中,您可以使用
$ids
$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>
因為您在調用模型之前調用了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);
在你看來像這樣的foreach
<?php foreach($Posts as $item): ?>
<?= item['id'] ;?> Or if you have STD Class <?= item->id ;?>
<?php endforeach; ?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.