我正在尝试创建一个简洁地给我以下内容的数组:
我使用的是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组,都有一组'卷'。
非常感谢任何建议......我一直在努力让数组排序!