php - CodeIgniter 中的 Foreach

标签 php mysql codeigniter

我想选择一些排除前 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/

相关文章:

php - 使用 codeigniter htaccess 在整个站点上强制使用 ssl

php - 如何在 jQuery.knob 中添加值后缀

java - Web表单提交未进入数据库

mysql - 避免子查询

php - 使用mysql插入数据时获取ID

php - 选择并计算字段

php - 使用 php mysql ajax 动态更新选择框

php - php codeigniter中的电话号码验证

php - Javascript 确认删除

php - 当用户按下按钮时,如何从 View 中更改模型内的值?