我想选择一些排除前 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;
}
Controller :$this->data["all_news"] = &$this->site_news->get_all_news_home();
最佳答案
改变这个。您应该在将其传递给 foreach 之前检查 null 条件。
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;
}
关于php - CodeIgniter 中的 Foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23215808/