codeigniter中的未定义变量

时间:2012-08-08 11:30:53

标签: arrays codeigniter view model foreach

CI中有这个错误:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: news

Filename: controllers/First.php

Line Number: 33

A PHP Error was encountered



Severity: Notice

Message: Undefined variable: news

Filename: views/welcome_view.php

Line Number: 1

A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: views/welcome_view.php

Line Number: 1

有我的控制器:

<?php
if ( ! defined('BASEPATH')) exit ('No direct script access allowed');

   class First extends CI_Controller
   {

    public function __construct()
    {
    parent::__construct();
    $this->load->model('materials_model');
    }    


    public function index()
      {
        $this->load->view('header_view');
        $this->load->view('menu_view');
        $this->load->view('about_me_view');
        $this->load->view('navigation_view');
        $this->load->view('search_view');
        $this->load->view('main_text_view');
        $this->load->view('footer_view');

      }


    public function mat()
    {
       $this->load->model('materials_model');
       $this->materials_model->get();
       $data['news'] = $this->materials_model->get();

       $this->load->view('welcome_view',$news);

       if(empty($data['news']))
       {
        echo'Array is Null';
       }

       else
       {
        echo'Array has info';
       }
    }

我的模特:

<?php
if ( ! defined('BASEPATH')) exit ('No direct script access allowed');

class Materials_model extends CI_Model
{
    public function get()
    {
        $query = $this->db->get('materials');
        return $query->result_array();
    }


}

?>

我的观点:

<?php foreach ($news as $one):?>
<?=$one['author']?>
<?php endforeach; ?>

所以我知道,我传入视图的数组是非NULL(我检查它是否为print_r和if,否则构造),但我可以传递它并查看它。我有什么错误?

3 个答案:

答案 0 :(得分:0)

$this->load->view('welcome_view',$news);
永远不会定义

$news。也许你的意思是使用$data ?, CI视图希望将一个关联数组传递给它们。

答案 1 :(得分:0)

设置变量:

$data['news'] = $this->materials_model->get();

将其传递给视图:

$this->load->view('welcome_view', isset($data) ? $data : NULL);

在视图中作为结果数组访问它:

<?php 
    foreach($news as $item)
    {
        echo $item['id']." - ".$item['some_other_column_title']
    } 
?>

作为一个选项,您可以在模型中更改get()方法以返回对象,而不是数组。

public function get()
{
    $query = $this->db->get('materials');
    return $query->result();
}

然后在视图中你需要处理$ news作为对象,如:

<?php 
    foreach($news as $item)
    {
        echo $item->id." - ".$item->some_other_column_title
    } 
?>

答案 2 :(得分:0)

在Controller中,您需要传递数据而非

之类的新闻
$data['news'] = 'Something';
$this->load->view('welcome_view',$data);

在您的视图中,您可以使用

foreach($news as $new)
{
   //Go Here
}