Php 归并阵
我正在尝试创建一个数组,该数组简洁地给出以下内容:Php 归并阵,php,mysql,laravel,Php,Mysql,Laravel,我正在尝试创建一个数组,该数组简洁地给出以下内容: 组件的ID 该部件的供应商ID 卷断点及其关联的单位成本 我使用的是Laravel5.2,尽管这是一个更一般的PHP问题 因此,我有一个如下所示的数据库表: 我有一个函数,如下所示,用于获取组件的一些价格: public function get_component_prices() { $components = DB::table('component_supplier') -&
- 组件的ID
- 该部件的供应商ID
- 卷断点及其关联的单位成本
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"
]
]
因此,对于每个组件id和供应商id组,都有一组“卷”
非常感谢您的建议。。。我已经试了几个小时来排序数组 在Mysql中,您可以这样做
选择组件id、供应商id、,
以卷为单位的集团成本(卷“:”,单位成本)
来自组件供应商
按CONCAT分组(组件id、供应商id)
然后,您可以简单地在PHP中循环此查询,并用逗号分解volumes字段