I have two arrays $patients and $escorts.
These arrays represent hospital stays for various patients and escorts. Escorts have a ['Escort']['id'] value that is associated with the ID of a Guest (Patient).
My goal is two take the Patients and Escorts arrays and combine them into a results array that can be used for printing (either a table, or creating an excel file).
Patients may have multiple stays, and a Patient may also have multiple Escorts escorting them.
$patients = [
Patient A,
Patient B,
Patient B
Patient C,
Patient D,
Patient E
];
$escorts = [
Escort for Patient B,
Escort 1 for Patient C,
Escort 2 for Patient C,
Escort for Patient E
];
I am trying to get the $newResults array in the following order:
$newResults = [
Patient A,
Patient B,
Patient B,
Escort for Patient B,
Patient C,
Escort for Patient C,
Escort for Patient C,
Patient D,
Patient E,
Escort for Patient E,
]
However, when I'm done iterating through both arrays I have leftover $escort elements that haven't been added after their $patient counterpart, yet going through the data the Patient's ['Guests']['id'] and the Escort's ['Escort']['id'] match, so I'm not sure why they're not being included.
The code I am using is:
$lastPatientID = 0;
foreach($patients as $pkey => $patient) {
if($lastPatientID == 0) {
$lastPatientID = $patient['Guests']['id'];
}
if($patient['Guests']['id'] == $lastPatientID) {
// Add Patients Next Accommodation
$newResults[] = $patient;
} else {
$theseEscorts = [];
foreach($escorts as $ekey => $escort) {
if($escort['Escort']['id'] == $lastPatientID) {
$theseEscorts[] = $escort;
unset($escorts[$ekey]);
}
}
// Print the escorts for the Last Patient.
foreach($theseEscorts as $anEscort) {
$newResults[] = $anEscort;
}
// This Patient is different than last. Print New Patient.
$newResults[] = $patient;
}
$lastPatientID = $patient['Guests']['id'];
}
// Clear any remaining escorts that match the last patient.
foreach($escorts as $escort) {
if($escort['Escort']['id'] == $lastPatientID) {
$newResults[] = $escort;
} else {
// NOTE:: THIS SHOULDN'T HAPPEN UNLESS DATA IS BAD!
error_log("Orphaned Escort: \n" . print_r($escort, TRUE) );
}
}
I must be making some logic mistake with this, although I'm not sure where.
Any advice is much apprecaited!