也许我正在寻找过去的东西,清晨。
我有一系列的处方'我从我的数据库中获取并将其存储在我的类中的公共变量中。 SQL调用后该数组的简单示例...
$prescriptions = [
0 => [
'companyName' => 'FoorBar Inc.',
'prescription' => 'SomePrescription',
'cost' => '$9.98',
],
1 => [
'companyName' => 'FoorBar Inc.',
'prescription' => 'SomeOtherPrescription',
'cost' => '$15.98',
],
2 => [
'companyName' => 'Labs Inc.',
'prescription' => 'SomePrescription',
'cost' => '$12.38',
],
3 => [
'companyName' => 'Lorem Ipsum Inc.',
'prescription' => 'SomePrescription',
'cost' => '$100.98',
],
4 => [
'companyName' => 'Lorem Ipsum Inc.',
'prescription' => 'SomePrescription',
'cost' => '$53.08',
],
];
现在我要做的是按公司对这些处方进行分组,但仍然保留处方所附的所有数据,所以我有以下逻辑:
public function groupByCompany()
{
$clinicArray = [];
foreach ($this->prescriptions as $prescription) {
$clinicArray[$prescription["companyName"]] = [];
}
foreach ($this->prescriptions as $prescription) {
$clinicArray[$prescription["companyName"]][] = $prescription;
}
return $clinicArray;
}
这很好用,我得到了我想要的结果。我觉得有更好的方法可以做到这一点,也许没有运行两次foreach循环。有什么建议吗?
谢谢大家。
答案 0 :(得分:2)
只有一个foreach
:
public function groupByCompany()
{
$clinicArray = [];
foreach ($this->prescriptions as $prescription) {
$companyName = $prescription["companyName"];
if (!isset($clinicArray[$companyName])) {
$clinicArray[$companyName] = [];
}
$clinicArray[$companyName][] = $prescription;
}
return $clinicArray;
}