如何在PHP中基于某些分组将mysql查询的结果拆分为多个数组?

我有php API(使用PDO)。我从客户端获取一些数据,并对其应用mysql查询,并从数据库接收查询结果。现在,我想要的是将查询结果拆分为多个数组(多维数组)。


就像Im将购物车的Item(11,12,13,17,17,18,19)ID发送到数据库查询一样,如下所示:


"SELECT s.SparePartID, s.Name, s.VendorID, v.CompanyName 

FROM sparepart s 

INNER JOIN users v

ON v.VendorID= s.VendorID

WHERE s.SparePartID IN ('11', '12','13', '17', '18', '19')"

以上查询结果如下:


+-------------+---------+----------+---------------------+

| SparePartID |   Name  | VendorID |     CompanyName     |

+=============+=========+==========+=====================+

|     11      |  Tyres  |    48    | Master Automotives  |

+-------------+---------+----------+---------------------+

|     12      |  Lights |    48    | Master Automotives  |

+-------------+---------+----------+---------------------+

|     13      |  Wheels |    48    | Master Automotives  |

+-------------+---------+----------+---------------------+

|     17      |  Torch  |    50    | *Repair Solutions*  |

+-------------+---------+----------+---------------------+

|     18      |   Lamp  |    50    | *Repair Solutions*  |

+-------------+---------+----------+---------------------+ 

|     19      | Camera  |    50    | *Repair Solutions*  |

+-------------+---------+----------+---------------------+

现在,我想它的保存群体的阵列其公司名称的基础上。因为此数据中有2个不同的公司名称,所以我想将此数据保存在2个数组的数组中,否则组数应等于不同的公司名称。


因此,我希望将荡妇分成几个部分:


[


"Group1": [


{

"SparePartID": "11",

"Name" : "Tyres",

"VendorID": "48",

"Company" : "Master Automotives"

},


{

"SparePartID": "12",

"Name" : "Lights",

"VendorID": "48",

"Company" : "Master Automotives"

},


{

"SparePartID": "13",

"Name" : "Wheels",

"VendorID": "50",

"Company" : "Master Automotives"

}


]



"Group2": [


{

"SparePartID": "17",

"Name" : "Torch",

"VendorID": "50",

"Company" : "*Repair Solutions*"

},


{

"SparePartID": "18",

"Name" : "Lamp",

"VendorID": "50",

"Company" : "*Repair Solutions*"

},


{

"SparePartID": "19",

"Name" : "Camera",

"VendorID": "50",

"Company" : "*Repair Solutions*"

}



]



]

现在,请任何人帮助我建议如何根据公司名称拆分结果?执行查询后,我应该修改查询还是修改结果数组吗?请帮助


森林海
浏览 254回答 2
2回答

MM们

只需更改此行:array_push($products_arr["records"], $product_item);对此:$products_arr["records"][$product_item["Company"]][] = $product_item;

呼唤远方

试试这个查询:SELECT s.SparePartID, s.Name, s.VendorID, v.CompanyName FROM sparepart s INNER JOIN users v ON v.VendorID= s.VendorID WHERE s.SparePartID IN ({$ids_arr}) **GROUP BY v.CompanyName**
打开App,查看更多内容
随时随地看视频慕课网APP