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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里