首页 > 解决方案 > Codeigniter foreach() 限制

问题描述

使用 Codeigntier 3

我试图将我的数据库内容限制为 5 个帖子。现在我的 foreach 工作正常,但我不知道如何将数字限制为 5。

我在网上找到的大部分东西都来自 codeigniter 2。

控制器

public function index(){

        $data['Sideposts'] = $this->Blog_Model->get_bposts();

模型

public function get_bposts($slug = FALSE){

if($slug === FALSE){

  $this->db->order_by('date','DESC');
  $query = $this->db->get('blogposts');
  return $query->result_array();
}

查看代码

<?php foreach($Sideposts as $Sidepost):{ ?>

                        <ul style="list-none;">

   <?php echo $Sidepost['title']; ?>

                        </ul>

                    <?php }endforeach; ?>

标签: phpcodeigniterloops

解决方案


public function get_bposts($slug = FALSE,$lmt=0){

if($slug === FALSE){

  $this->db->order_by('date','DESC');
  if($lmt>0)
  {
       $query = $this->db->get('blogposts',$lmt);
  } else {
       $query = $this->db->get('blogposts');   
  }
  return $query->result_array();
}

使用它如下:

$data['Sideposts'] = $this->Blog_Model->get_bposts(FALSE,5);

推荐阅读