dongshi3818 2015-10-07 19:26
浏览 60
已采纳

从codeigniter中的foreach循环返回一行

I have this model:

public function get_products_by_slug($slug)
    {
        $this->db->select('*');
        $this->db->from('products');
        $this->db->where('slug', $slug);
        $query = $this->db->get();
        return $query->result(); 
    }

And this controller:

public function products($category)
    {

        $data['products_by_category'] = $this->products_model->get_products_by_slug($category);

        if (empty($data['products_by_category']))
        {
            show_404();
        }

        $data['main_content'] = 'pages/products_by_category';
        $this->load->view('templates/template', $data);
    }

And in the view for the title of the page as a banner in the page I want to use both those function to grab just the first category field in the database to use it as the title. I know that there is way in the model that I can grab just the first row. But what I want is not make another model just for that I want to use those functions above to use it for the title and the rest of the page to show the all products.

the view page:

<?php foreach($products_by_category as $row){
    echo '<div class="container">';
    echo '<h1>'.$row->category(1).'</h1>';
    echo '<hr/>';
    echo '</div>'; } ?>

now this way above it will make as much with the same name of the category as there is in the database. what I want is only one name for the title.

  • 写回答

1条回答 默认 最新

  • donglang2010 2015-10-07 21:32
    关注

    After a lot of searching around the web the answer was so simple. You don't need the foreach loop just use the passed variable with the number of the row in the array and the name of the field. just like that.

    <?php
        echo '<div class="container">';
            echo '<h1>'.$products_by_category[1]['category'].'</h1>';
            echo '<hr/>';
        echo '</div>'; 
      ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?