How to separate the results of a SELECT in MYSQL into 2 foreach in PHP?

Asked

Viewed 443 times

1

I have a recipes website where I bring the list of recipes according to the query below:

SELECT * FROM receitas WHERE titulo LIKE '%batata%' ORDER BY ordem

I wanted to show the first 3 featured results (with a different CSS class) and the rest below.

I thought to do 2 foreach, the first with the first 3 highlight and the other foreach with the rest of the results.

My question: This is the best way? If yes, how can I make the 2nd foreach discount those who have already appeared in the 1st not to repeat?

I would like the end result to be:

<h2>Destaques</h2>
<div>
  <div class="destaque">Destaque 1</div>
  <div class="destaque">Destaque 2</div>
  <div class="destaque">Destaque 3</div>
</div>
<h2>Outros</h2>
<div>
  <div class="comum">Outro 1</div>
  <div class="comum">Outro 2</div>
</div>

1 answer

4


Use only one foreach. Example:

<h2>Destaques</h2>
<div>
<?
foreach($receitas as $idx => $r) {
    if($idx <= 2) {
        echo '<div class="destaque">...</div>';
    }elseif($idx == 3) {
        echo '</div><h2>Comuns</h2><div>';
            echo '<div class="normal">...</div>';
        }elseif($idx > 3) {
            echo '<div class="normal">...</div>';
        }
    }
echo '</div>';

Note that the idx used in condition is less than or equal to 2 as this starts at 0.

0 = Revenue 01

1 = Recipe 02

2 = Revenue 03

I hope I’ve helped.

  • show, is that like joining the foreach with the is? a doubt on this, is that I would like to put a <H2> between the highlights and the common ones, I edited my question as I need the final result.

  • I got it using what you sent and a combination of ifs, I can edit your reply and put as solved?

  • Hello. Foreach and For are efficient loop loops, but foreach is used to traverse arrays or objects. I’m glad you made it! Yes, you can.

Browser other questions tagged

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