foreach within the foreach without repeating the data

0

I have a listing of Employees and each employee can have many Cost Centers.

And as far as I get information from the bank employee I need to list the cost centers and list the cost centers where the employee is registered by marking the selected as selected.

$intCentroCustoId = $this->modelo->arrComboCentroCustoFuncionario; // traz o array da listagem de centros de custo que o funcionario está cadastrado
    $arrComboBar = $this->modelo->arrComboBar; // traz todos os centros de custos
    /*echo '<pre>';
    var_dump($intCentroCustoId);
    echo '</pre>';*/

    echo "<select data-minlength-error='Selecione pelo menos um'
                                                data-placeholder='Digite ou selecione' data-minlength='1'
                                                multiple='multiple' name='arrCentroCusto[]'
                                                id='arrCentroCusto'
                                                class=\"js-basic-multiple form-control\" required>"; // monta a select multiplo
    if(isset($arrComboBar) && !empty($arrComboBar)){ // verifica se a combo não esta vazia
        echo "<option></option>";//primeiro option vazio
        foreach($arrComboBar as $arrLinha){ //listagem completa dos centros de custos
            foreach ($intCentroCustoId as $CC)
                    if($CC['id_centro_custo'] == $arrLinha['idcusto']){
                        echo "<option value='".$CC['id_centro_custo']."' selected>";
                        echo utf8_decode($arrLinha['departamento']);
                        echo "</option>";
                    }

                    else{
                        echo "<option value='".$arrLinha['idcusto']."'>";
                        echo utf8_decode($arrLinha['departamento']);
                        echo "</option>";
                    }


        }

    }
    echo "</select>";

My problem is that the listing gets repeated, depending on how many cost centers the employee is registered with.

How do I list all cost centers with the 3 selected and not repeated?

    
asked by anonymous 25.10.2018 / 19:51

1 answer

0

Man, the problem is that your echo of the option is within 2 foreachs , so it will repeat, I took the echo from within one of the foreach and gave a summary in your code:

if(isset($arrComboBar) && !empty($arrComboBar)){ // verifica se a combo não esta vazia

    echo "<option></option>";//primeiro option vazio

    foreach($arrComboBar as $arrLinha){ //listagem completa dos centros de custos
      foreach ($intCentroCustoId as $CC){

        if($CC['id_centro_custo'] == $arrLinha['idcusto']){
          $selected = ' selected';
          break;
        }else{
          $selected = '';
        }

      }

      echo "<option value='".$arrLinha['idcusto']."'".$selected.">";
      echo utf8_decode($arrLinha['departamento']);
      echo "</option>";

    }
}
    
25.10.2018 / 21:06