duanbimo7212 2015-08-28 19:02
浏览 10
已采纳

在一个查询中选择所有项目和相关项目

I'm using latest codeigniter

I'm trying to get all products from the db and all related items for each product. Haven't coded for a while so I got stuck on output..

Here's my model:

   public function collections() {

        $this->db->select('*');
        $this->db->from('products');
        $this->db->join('product_images', 'product_images.from_set = products.img_set_ref');
        $this->db->order_by('products.id');

        $q = $this->db->get();         

        if ($q->num_rows() > 0) {       
            return $q->result();        
        }
        return false;               
    }

Controller:

    public function products() {   
    $this->load->model('Frontend'); 
    $page_data['results'] = $this->Frontend->collections();       
    $this->load->view('collections', $page_data);           
}

This is the output I'm trying to get (example of two products):

            <div class="pr"> //product 1
            <a href="img/pr_1.jpg" rel="gallery01"><img src="img/pr.jpg" alt="">
            </a>
            <a href="img/pr_2.jpg" rel="gallery01"><img src="img/pr.jpg" alt="">
            </a>
        </div>

        <div class="pr"> //product two
            <a href="img/pr_12.jpg" class="fancybox" rel="gallery02"><img src="img/pr.jpg" alt="">
            </a>
            <a href="img/pr_22.jpg" class="fancybox" rel="gallery02"><img src="img/pr.jpg" alt="">
            </a>
        </div>

I can't figure out how to properly echo products in foreach loop in the view so that they were in structure like above. How to achieve that?

  • 写回答

3条回答 默认 最新

  • duan0708676887 2015-08-28 20:02
    关注

    If I would need a fast'n'dirty way, I'd go with building a temporary array of images per product

    $groupedProducts = array();
    foreach ($products as $product) {
         if (!array_key_exists($product['id'], $groupedProducts) {
             $groupedProducts[$product['id']] = $product;
             $groupedProducts[$product['id']]['images'] = array();
         }
         $groupedProducts[$product['id']]['images'][] = $product['product_images.url'];
    }
    

    Then iterate

    foreach ($groupedProducts as $product) {
        // output some description, title, price, etc.
        foreach ($product['images'] as $imageUrl) {
            echo '<img src="'.$imageUrl.'">';
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?