【问题标题】:Return category and forums in query?返回查询中的类别和论坛?
【发布时间】:2012-03-04 15:34:54
【问题描述】:

我目前正在 CodeIgniter 中开发一个简单的论坛来处理 PHP,但我遇到了一个问题,虽然很初级。

我的论坛索引由类别组成,每个类别都分配有几个论坛。我想显示每个类别的标题,然后返回下面的每个论坛。

这是我目前返回数据的模型:

function get_top_level_forums()

{

    $this->db->select('id, title');
    $this->db->from('forum_category');
    $query = $this->db->get();

    if ($query->num_rows() > 0)

    {

        $categories = $query->result();

        foreach($categories as $category)

        {

            $this->db->select('id, title, description');
            $this->db->from('forum');
            $this->db->where('parent_id', 0);
            $this->db->where('category_id', $category->id);
            $query = $this->db->get();

            $forums = $query->result();

        }

        return $categories;

    }

}

我正在努力研究如何在单个数组中返回所有数据。我知道这是一个菜鸟问题,但我已经戳了一个小时,在隧道尽头看不到任何光线!

我知道如何使用我的 CONTROLLER 和 VIEW 中的数据。我只是停留在模型部分。

谢谢。

:)

【问题讨论】:

    标签: php sql codeigniter


    【解决方案1】:

    将内部查询的结果放入循环内的数组中,然后返回该数组。

    【讨论】:

      【解决方案2】:

      不要使用变量来存储结果,而是使用数组

      $forums[] = $query->result();
      

      完整示例:

      $forums = array();
      foreach($categories as $category)
      
              {
      
                  $this->db->select('id, title, description');
                  $this->db->from('forum');
                  $this->db->where('parent_id', 0);
                  $this->db->where('category_id', $category->id);
                  $query = $this->db->get();
      
                  $forums[] = $query->result();
      
              }
              //$forums now contains all the query results
      

      更新

      要访问您可以使用的变量

      $forums[$forumindex][0] -> id;
      

      【讨论】:

      • 太棒了。这将返回论坛。我如何还返回类别标题并显示它?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-18
      • 2022-01-06
      相关资源
      最近更新 更多