CodeIgniter教程中foreach循环的错误
问题描述:
我想通过CodeIgniter教程工作,并且我的新闻页面不会从foreach循环输出数据。我得到以下信息:CodeIgniter教程中foreach循环的错误
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: news
Filename: pages/index.php
Line Number: 1
和
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: pages/index.php
Line Number: 1
这是我的模型类:
<?php
class News_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_news($slug = FALSE)
{
if ($slug === FALSE)
{
$query = $this->db->get('news');
return $query->result_array();
}
$query = $this->db->get_where('news', array('slug' => $slug));
return $query->row_array();
}
public function index()
{
$data['news'] = $this->news_model->get_news();
$data['title'] = 'News archive';
$this->load->view('templates/header', $data);
$this->load->view('news/index', $data);
$this->load->view('templates/footer');
}
}
而且我的控制器:
class News extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('news_model');
}
public function index()
{
$data['news'] = $this->news_model->get_news();
}
public function view($slug)
{
$data['news_item'] = $this->news_model->get_news($slug);
if (empty($data['news_item']))
{
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('templates/footer');
}
}
而且第一种观点:
<h2><?php echo $news_item['title'] ?></h2>
<div id="main">
<?php echo $news_item['text'] ?>
</div>
<p><a href="news/<?php echo $news_item['slug'] ?>">View article</a></p>
<?php endforeach ?>
与第二:
<?php
echo '<h2>'.$news_item['title'].'</h2>';
echo $news_item['text'];
我知道大概有教程其他问题,但似乎没有帮助我。
谢谢。
答
在模型中,你已经在构造函数后关闭了你的类。毕竟应该关闭功能。 另外view()被初始化两次。
+0
您好,谢谢。我做了这些改变,但它仍然不起作用,我得到了同样的错误。感谢您的帮助,我会再次查看我的代码并检查是否有其他愚蠢的错误。 – Haych
函数视图($ slug)在控制器中定义了两次 – Arunu