Duplicate items in Foreach

Asked

Viewed 324 times

1

I have two Inputs (curso[] and formacao[]) html and when loop with the foreach and starts to duplicate the items that are within the second foreach

This is my class

class Pessoa {

private $Formacao;
private $Cursos;

function __construct($Formacao,$Cursos)
{

    $this->Formacao =  (array) $Formacao;
    $this->Cursos = (array) $Cursos;
}

public function setFormacao($Formacao){
    $this->Formacao = $Formacao;
}

public function getFormacao(){

    return $this->Formacao;
}

public function setCursos($Cursos){
    $this->Cursos = $Cursos;
}

public function getCursos(){
    return $this->Cursos;
}

public function getBody(){

    foreach ($this->getFormacao() as $formacao) {
            $body = "<ul><li>{$formacao}";
            foreach ($this->getCursos as $cursos) {
                $body.= "{$cursos}</li></ul>";
            }   
    }

    return $body;
}
  • 2

    I’m not sure but I believe that you should not have the forechs chained, should be separated, can confirm this?

  • What is the relationship like? It is a course for a training?

  • I don’t know where this information comes from, the most reliable would be to have the course id of training in the database, so you know exactly which courses are in which formations, only with the question code it seems that they are separated.

  • I did not understand the relationship of the Formation with the Courses since the two are independent arrays. If it is a formation, with several courses, coming these two separate arrays, as you visualize correctly link the courses to the corresponding formations?

  • Shouldn’t it be private $Training[]; private $Courses[];? Otherwise it doesn’t make sense the setFormation since the builder already does this!

  • This data is not generated in a database.

  • 1

    @William does not need to add SOLVED in the title, the site works different from forums, and we recommend you post as a response below the way you solved the problem, and mark as accepted by clicking on v

Show 2 more comments

1 answer

1


I ended up finding the solution. It was very simple to use for instead of foreach, which is better to control iterations.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.