title: How to optimize foreach loop in PHP
body: <p>First off, I know the title is generic and not fitting. I just couldn't think of a title that could describe my problem.</p>
  
  <p>I have a table Recipients in MySQL structured like this:</p>
  
  <pre><code>id   |   email   |   status
  1      foo@bar         S
  2      bar@baz         S
  3      abc@def         R
  4      sta@cko         B
  </code></pre>
  
  <p>I need to convert the data into the following XML, depending on the <strong>status</strong> field. For example:</p>
  
  <pre><code>&lt;Recipients&gt;
      &lt;RecipientsSent&gt;
          &lt;!-- Have the 'S' status --&gt;
          &lt;recipient&gt;foo@bar&lt;/recipient&gt;
          &lt;recipient&gt;bar@baz&lt;/recipient&gt;
      &lt;/RecipientsSent&gt;
  
      &lt;RecipientsRegexError&gt;
          &lt;recipient&gt;abc@def&lt;/recipient&gt;
      &lt;/RecipientsRegexError&gt;
  
      &lt;RecipientsBlocked&gt;
          &lt;recipient&gt;sta@cko&lt;/recipient&gt;
      &lt;/RecipientsBlocked&gt;
  &lt;/Recipients&gt;
  </code></pre>
  
  <p>I have this PHP code to implement this ($recipients contains an associative array of the db table):</p>
  
  <pre><code>&lt;Recipients&gt;
  
  &lt;RecipientsSent&gt;
  &lt;?php
  foreach ($recipients as $recipient):
      if ($recipient['status'] == 'S'):
          echo "&lt;recipient&gt;" . $recipient['email'] . "&lt;/recipient&gt;";
      endif;
  endforeach;
  ?&gt;
  &lt;/RecipientsSent&gt;
  
  &lt;RecipientsRegexError&gt;
  &lt;?php
  foreach ($recipients as $recipient):
      if ($recipient['status'] == 'R'):
          echo "&lt;recipient&gt;" . $recipient['email'] . "&lt;/recipient&gt;";
      endif;
  endforeach;
  ?&gt;
  &lt;/RecipientsRegexError&gt;
  &lt;?php /** same loop for the B status */ ?&gt;
  
  &lt;/Recipients&gt;
  </code></pre>
  
  <p>So, this means that if I have 1000 entries in the table and 4 different status' that can be checked, it means that there will be 4 loops, each one executing 1000 times.</p>
  
  <p>How can this be done in a more efficient manner? I thought about fetching four different sets from the database, meaning 4 different queries, would that be more efficient? I'm thinking it could be done with one loop but but I can't come up with a solution.</p>
  
  <p>Any way this could be done with only one loop?</p>