简体   繁体   English

从Codeigniter中的foreach循环返回一行

[英]Returning one row from foreach loop in codeigniter

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. 我想要的只是标题的一个名称。

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. 您不需要foreach循环,只需将传递的变量与数组中的行号和字段名一起使用即可。 just like that. 就这样

<?php
    echo '<div class="container">';
        echo '<h1>'.$products_by_category[1]['category'].'</h1>';
        echo '<hr/>';
    echo '</div>'; 
  ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM