Maybe I am looking past something, early morning.
I have an array of 'prescriptions' that I get from my database and I store it in a public variable in my class. A quick example of what that array looks like after the SQL call...
$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',
],
];
Now what I am looking to do is group these prescriptions by company but still persist all data attached to the prescription, so I have the following logic:
public function groupByCompany()
{
$clinicArray = [];
foreach ($this->prescriptions as $prescription) {
$clinicArray[$prescription["companyName"]] = [];
}
foreach ($this->prescriptions as $prescription) {
$clinicArray[$prescription["companyName"]][] = $prescription;
}
return $clinicArray;
}
This works just fine, I get my desired result. I just feel like there is a better way to do this and maybe without running a foreach loop twice. Any suggestions?
Thank You Everyone.