How to group array data returned by left join query in php?

前端 未结 2 744
悲&欢浪女
悲&欢浪女 2021-01-23 10:11

I have following 2 tables with following values:


tbl_brand

id      name

<
2条回答
  •  北海茫月
    2021-01-23 10:48

    While you can generate the desired array in a single loop, I would rather execute two queries. First fetch all brands into an array and add an empty products array to every brand. Then fetch all products and assign them to the related brand.

    Since I don't know what DB library you are using, here some kind of pseudo code:

    $data = [];
    
    $brandResult = $db->query("SELECT id, name FROM tbl_brand");
    while ($row = $brandResult->fetchObject()) {
        $row->product_names = [];
        $data[$row->id] = $row;
    }
    
    $productResult = $db->query("SELECT id, brand_id, p_name FROM tbl_products");
    while ($row = $productResult->fetchObject()) {
        $data[$row->brand_id][$row->id] = $row->p_name;
    }
    

提交回复
热议问题