compare Sql data with two Foreach

Asked

Viewed 79 times

0

I’m looking for data from two tables which have an equal column, which is called the prefix column.

I tried to mount a foreach inside the other foreach with the data of the two tables and comparing the values for when they are equal, ie the prefix was in the two tables changed the color of the button to green, if the prefix(value) is only in a table put the color red, do this along with creating the button through PHP.

 <?php
       foreach($produtos as $produto) {
   ?>

    <section class="abastecimento">
    <button class="pack detail btn" <?php         

                foreach($abastecimentos as $abastecimento) {

                    if ($abastecimento['prefixo'] == $produto['prefixo']) {
                       echo "style='background-color:green'";  
                    }else{
                        echo "style='background-color:red'";                        
                    }
                }     

            ?>  id="detail"><?php echo trim($produto['prefixo']);   ?>      

    </button>


    </section>


   <?php
       }
   ?>

The first prefix comes with the color green, the second also in the two tables does not paint.

1 answer

1


The way you are doing will go wrong, because the second foreach will generate several attributes style on the button due to the fact that when the if is not satisfied, will enter the else and create a style each loop in the loop, causing HTML error.

Create a boolean variable and only insert the style with the red button if the if the second foreach has not been satisfied:

<?php
foreach($produtos as $produto) {
   $bool = false;
?>
<section class="abastecimento">
   <button class="pack detail btn" <?php         

      foreach($abastecimentos as $abastecimento) {

         if ($abastecimento['prefixo'] == $produto['prefixo']) {
            echo "style='background-color:green'";
            $bool = true; // altera a variável
            break; // para o laço porque já encontrou um igual
         }
      }     

      if(!$bool){
         echo "style='background-color:red'";                        
      }

?>  id="detail"><?php echo trim($produto['prefixo']);   ?>      
   </button>
</section>
<?php
}
?>

Browser other questions tagged

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