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

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

I have following 2 tables with following values:


tbl_brand

id      name

<
相关标签:
2条回答
  • 2021-01-23 10:45

    mysql returns rows, so if you want a multidimensional array you have to construct it yourself. A loop along these lines will do it:

    $array=array();
    foreach ($result as $row) {
        $array[$row->brandid]['brandid'] = $row->brandid;
        $array[$row->brandid]['brand_name'] = $row->brand_name;
        $array[$row->brandid]['products'][] = $row->product;
        }
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题