减少和合并阵列
问题描述:
我试图创建一个数组,简要地给了我下面的:一个组成部分 减少和合并阵列
- ID,和他们相关的单位成本
我使用Laravel 5.2,虽然这是一个更一般的PHP问题。
所以,我有一个数据库表,看起来像这样:
我有一个函数,如下,以获得部件的部分产品价格:
public function get_component_prices()
{
$components = DB::table('component_supplier')
->select('component_id', 'supplier_id', 'volume', 'unit_cost')
->get();
$prices = [];
foreach ($components as $component) {
array_push($prices, ["component_id" => $component->component_id, "supplier_id" => $component->supplier_id, "volumes" => [$component->volume => $component->unit_cost]]);
}
dd($prices);
}
这给了我阵列:
array:7 [▼
0 => array:3 [▼
"component_id" => 3
"supplier_id" => 1
"volumes" => array:1 [▼
100 => "1.5000"
]
]
1 => array:3 [▼
"component_id" => 3
"supplier_id" => 1
"volumes" => array:1 [▼
207 => "1.0100"
]
]
2 => array:3 [▼
"component_id" => 3
"supplier_id" => 1
"volumes" => array:1 [▼
500 => "0.8000"
]
]
3 => array:3 [▼
"component_id" => 3
"supplier_id" => 1
"volumes" => array:1 [▼
1000 => "0.4000"
]
]
4 => array:3 [▼
"component_id" => 3
"supplier_id" => 2
"volumes" => array:1 [▼
10000 => "0.2000"
]
]
5 => array:3 [▼
"component_id" => 4
"supplier_id" => 2
"volumes" => array:1 [▼
100 => "0.1000"
]
]
6 => array:3 [▼
"component_id" => 4
"supplier_id" => 2
"volumes" => array:1 [▼
500 => "0.0700"
]
]
]
您可以看到某些供应商并且组件具有多个卷。
因此,我想尝试组排列好一点,合并重复的部分 - 也许像这样,例如:
6 => array:3 [▼
"component_id" => 4
"supplier_id" => 2
"volumes" => array:3 [▼
100 => "0.1000",
500 => "0.0700"
]
]
因此,对于每个COMPONENT_ID和supplier_id组,有一个一套'卷'。
任何意见是非常赞赏......我一直在尝试几个小时,以获得数组排序!
答
在MySQL中,你可以做这样的事情
SELECT component_id, supplier_id,
GROUP_CONCAT(volume, ':', unit_cost) AS volumes
FROM component_supplier
GROUP BY CONCAT(component_id, supplier_id)
http://sqlfiddle.com/#!9/cb7bb/1
然后,您可以通过逗号在PHP简单地循环这个查询和爆炸卷场。