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>'; 
      ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)