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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵