Foreach inside foreach is doubling PHP values?

Asked

Viewed 280 times

1

I’m having a problem looping, I am working with 3 tables of the Bank, would be table Anuncio, Opcoes_Anuncio(interconnected) and Opcoes, I’m trying to bring the option data along with the selected options, but it turns out it’s giving several looping.

MYSQL

my query is like this

SELECT * FROM opcoes op INNER JOIN opcoes_anuncio oa ON oa.opcoes_id_opcao = op.id_opcao INNER JOIN anuncio an ON oa.anuncio_id_anuncio = an.id_anuncio WHERE an.anuncio_id_anuncio = '17' ORDER BY op.id_opcao ASC

PHP

<?php foreach ($opcoes as $val): ?>
    <div class="form-group form-check">
      <input type="checkbox" class="form-check-input" name="opcoes_id_opcao[]"
              value="<?= $row->id_opcao; ?>"
              id="<?= $row->slug_opcao; ?>" 
            <?php if($row->id_opcao == $val->opcoes_id_opcao) { echo "checked"; }?> >
        <label class="form-check-label" for="<?= $row->slug_opcao; ?>">
           <?= $row->titulo_opcao; ?>
        </label>
        </div>
<?php endforeach; ?>
<?php endforeach; ?>

IMAGEM DO ERRO DE LOOPING

  • What’s your idea in this loop?

  • You have to describe much more to get a satisfactory answer. what you have $show_opcoes ? and what has $opcoes ? what html result these two for’s give and what would be the right one ?

  • Okay, I had forgotten to upload the image, with it becomes much easier to visualize the error that happens

  • In your SQL you have an error, here should be WHERE an.id_anuncio, but other than that the query does not return duplicated records unless they have actually been recorded the same ad option more than once. Post the code of your 2 foreach, the problem must be there.

  • I think it is error in the same Foreach, but I’m trying to bring the normal values that would OPTIONS and also bring the chosen marked values before it is OPCOES_ANUNCIOS, when I do right, it only returns me the 3 marked, but I need the OPTIONS values so that the person selects another option

1 answer

1

Hello, hard to know why this occurs without seeing the structure of the tables, but a group by opcoes_anuncio.anuncio_id_anuncio can solve the problem.

Besides, it seems your code isn’t right, it has 2 endforeach, and vc iterates with the variable $val, but below uses $row. It seems that the code is wrong or incomplete.

  • I think it is error in the same Foreach, but I’m trying to bring the normal values that would OPTIONS and also bring the chosen marked values before it is OPCOES_ANUNCIOS, when I do right, it only returns me the 3 marked, but I need the OPTIONS values so that the person selects another option

  • 1

    In this case, use LEFT JOIN would not solve? If you can put the structure of the tables would facilitate.

Browser other questions tagged

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