如何分组PHP数组结果

时间:2015-10-24 15:44:42

标签: php sql arrays

我的表格包含以下字段patchnoProject_no Item_Desc Quantity Store Action 目前它看起来像这样:

enter image description here

我希望如此:

enter image description here

每个patch_no必须具有唯一的project_no并且存储其他两列是多样的。 我的数组变量是PHP,如果我使用print_r($orders)它输出它。

Array ( [0] => stdClass Object ( [ID] => 1 [patchno] => 1 [item_id] => 1 [Quantity] => 10 [store_id] => 1 [project_id] => 1 [user_id] => 1 [order_date] => 2015-10-22 14:55:51 [Desc] => Jiingado [Cost] => 6.60 [store_name] => Nuux [Telephone] => 565656 [email] => email@nuux.com [address] => Gacanlibaax [Project_No] => 466 [Site] => A [owner] => Gaboose [foreman] => Axmed Diiriye ) [1] => 
 stdClass Object ( [ID] => 1 [patchno] => 1 [item_id] => 3 [Quantity] => 2 [store_id] => 1 [project_id] => 1 [user_id] => 1 [order_date] => 2015-10-22 14:55:51 [Desc] => Marmar [Cost] => 1.00 [store_name] => Nuux [Telephone] => 565656 [email] => email@nuux.com [address] => Gacanlibaax [Project_No] => 466 [Site] => A [owner] => Gaboose [foreman] => Axmed Diiriye ) [2] => stdClass Object ( [ID] => 1 [patchno] => 1000002 [item_id] => 2 [Quantity] => 21 [store_id] => 1 [project_id] => 1 [user_id] => 1 [order_date] => 2015-10-24 15:34:52 [Desc] => Masaabiir [Cost] => 2.00 [store_name] => Nuux [Telephone] => 565656 [email] => email@nuux.com [address] => Gacanlibaax [Project_No] => 466 [Site] => A [owner] => Gaboose [foreman] => Axmed Diiriye ))

输出这些值的查询是:

SELECT orders.*, items.*, stores.*, projects.*
            FROM orders
            join items on items.ID=orders.item_id
            join stores on stores.ID=orders.store_id
            join projects on projects.ID=orders.project_id

1 个答案:

答案 0 :(得分:1)

使用group_concat获取组中所有“变种”值的逗号分隔字符串,并且应在group by中指定组的唯一值:

select patchno, Project_no, group_concat(Item), group_concat(Quantity), store
from orders
join items on items.ID=orders.item_id
join stores on stores.ID=orders.store_id
join projects on projects.ID=orders.project_id
group by patchno, project_no, store