Nested foreach loop with IF expression

Database Tables:

movie (id_film PK, name)

genre (id_genre PK, name)

film_genre (id_film FK, id_genre FK)

This displays all genres from the genre table:

$genremenu = $veza -> prepare("select * from genre");
$genremenu -> execute();
$resultmenu = $genremenu -> fetchALL(PDO::FETCH_OBJ);

This displays all the selected genres from the film_genre table for a particular film:

$izraz = $veza -> prepare("select * from genre a inner join film_genre b on a.id_genre=b.id_genre where b.id_film=:id_film");
$izraz -> execute(array("id_film" => $film -> id_film));
$selectedgenre = $izraz -> fetchAll(PDO::FETCH_OBJ);

I had a problem with outputting data from a database to several selected lists in a form. This is a movie database, and I do a foreach iteration to read all the lines of the movie genres for output to multiple selection fields. But I had problems with the conclusion of the "selected" genres in this list. the code

foreach ($resultmenu as $line) {
    foreach ($selectedgenre as $sg) {
       if ($line-> id_genre === $sg-> id_genre) {
          echo "<option value=\"" . $line-> id_genre . "\" selected>" . $line-> name . "</option>";
        } else {
          echo "<option value=\"" . $line-> id_genre . "\">" . $line-> name . "</option>";
           }
        }

      }

, , , , 2 , " ", , $ , $selectedgenre, :

  • ""
  • ""
  • Horror
  • Horror
  • .

php, , ? , , ? , ( ) . !

+4
2

U , , , .

<?php

$genres = array();
foreach ($selectedgenre as $sg) {
   $genres[] = $sg->id_genre;
}


foreach ($resultmenu as $line) {

   if (in_array($line->id_genre,$genres)) {
      echo "<option value=\"" . $line->id_genre . "\" selected>" . $line->name . "</option>";
    } else {
      echo "<option value=\"" . $line->id_genre . "\">" . $line->name . "</option>";
    }
}

?>
+2

, :

$out=array();
foreach ($resultmenu as $line) {
$out[$line-> id_genre]=$line;
}

distinct(id_genre) select group by id_genre

foreach id_genre

foreach ($selectedgenre as $sg) {
       if ($line-> id_genre === $sg-> id_genre) {

inarray

+2

Source: https://habr.com/ru/post/1653770/


All Articles