我想选择一些排除前4条的新闻,但我得到了一个错误为foreach提供的参数无效:型号:
public function get_all_news_home()
{
$exclude = array();
$this->load->database();
$last_news_query = $this->db->query("SELECT * FROM News WHERE Type = 1 AND Ready='Y' ORDER BY Date DESC LIMIT 4");
$last_news = $this->db->query($last_news_query);
$last_news = ($last_news->num_rows()) ? $last_news->result_array() : NULL;
foreach ($last_news as $ln)
{
array_push($exclude,array('id' => $ln['ID']));
}
$newsIds = implode(',', array_values($exclude));
$all_news = $this->db->query("SELECT * FROM News WHERE News.Ready = 'Y' AND News.ID NOT IN ('$newsIds') ORDER BY Date DESC LIMIT 12");
if($all_news->num_rows())
{
$all_news = $all_news->result_array();
}
else
{
$all_news = NULL;
}
return $all_news;
}
控制器:$this->data["all_news"] = &$this->site_news->get_all_news_home();
更改此项。在将null条件传递给foreach之前,您应该检查它。
public function get_all_news_home()
{
$exclude = array();
$this->load->database();
$last_news_query = $this->db->query("SELECT * FROM News WHERE Type = 1 AND Ready='Y' ORDER BY Date DESC LIMIT 4");
$last_news = $this->db->query($last_news_query);
$last_news = ($last_news->num_rows()) ? $last_news->result_array() : NULL;
$all_news = NULL;
if($last_news!=NULL){
foreach ($last_news as $ln)
{
array_push($exclude,array('id' => $ln['ID']));
}
$newsIds = implode(',', array_values($exclude));
$all_news = $this->db->query("SELECT * FROM News WHERE News.Ready = 'Y' AND News.ID NOT IN ('$newsIds') ORDER BY Date DESC LIMIT 12");
if($all_news->num_rows())
{
$all_news = $all_news->result_array();
}
}
return $all_news;
}
我认为这个简单的函数应该很适合您。请使用这个简单的函数,让我们知道发生了什么。
public function get_all_news_home()
{
$this->load->database();
$all_news = $this->db->query("SELECT * FROM News WHERE Type = 1 AND Ready = 'Y' ORDER BY Date DESC LIMIT 4, 12");
if($all_news->num_rows())
{
$all_news = $all_news->result_array();
}
else
{
$all_news = NULL;
}
return $all_news;
}
$exclude = array();
$this->load->database();
$last_news = $this->db->query("SELECT * FROM News WHERE Type = 1 AND Ready='Y' ORDER BY Date DESC LIMIT 4");
//$last_news = $this->db->query($last_news_query);
//remove this line you are re-executing the query.
$last_news = ($last_news->num_rows()) ? $last_news->result_array() : NULL;
//before foreach add if condition
if (!is_null($last_news)) {
//add your code
}
在foreach
之前添加if
条件总是一种很好的做法。我希望这对你有帮助。