vendredi 12 janvier 2018

get rid of nested foreach loop

Recently I have been confronted with some annoying issue regarding nested foreach loops.

Could someone point me into right direction or give me some hint how to get rid of the nested foreach loop properly? I had so far shifted the nested foreach into the Doctor class and iterate there over all diagnosis ... but it seems not to be the desired approach... I'm missing here some basically unterstanding for desing patterns?

  Class Treatment { 


 /**
 *  get Diagnosis and releated Doctors information (this is an temporary approach)
 */
public function getDiagnosis(){

    $diagnosisContainer = [];
    foreach($this->doctorIterator as $key => $doc){ //iterate all doctors
        //how to get rid of this nested foreach ?
        foreach($doc->getCurrentDiagnosis() as $diagnosis) { //iterate all diagnosis
            $std = new \StdClass();
            $std->docType      = $doc->getType();
            $std->docLastname  = $doc->getLastname();
            $std->docFirstname = $doc->getFirstname();
            $std->diagnosis    = $diagnosis;
            $diagnosisContainer = array_merge([$std], $diagnosisContainer);
        }
    }
    return $diagnosisContainer;
}  }

And this is my proposed solution so far, where the iterator is only moved into Doctor class, but generally the same to me.

 public function getDiagnosis($type = 0){

    $diagnosisContainer = [];
    foreach($this->doctorIterator as $key => $doc){ //iterate all doctors

        $diagnosisContainer = array_merge($diagnosisContainer, $doc->getDiagnosisWithDoctor());  }

Aucun commentaire:

Enregistrer un commentaire