title: Foreach loop in PHP - looping through an array of results, displaying them in a single table row in HTML?
body: <p>I have a table of orders that I am querying for totals, and I want to display them all by quarter. Here is the query:</p>
  <pre class="lang-sql prettyprint-override"><code>SELECT shipping_number, SUM(qty) AS qty, SUM(cost) AS cost, 
  QUARTER( TIME ) AS quarter
  FROM order_items
  WHERE 1 
  GROUP BY quarter, shipping_number
  ORDER BY quarter, shipping_number
  </code></pre>
  <p>And I have a simple table row in which I want to display these results in:</p>
  <pre><code>echo &quot;&lt;tr&gt;&quot;;
  echo '&lt;th colspan=&quot;2&quot; style=&quot;text-align: right !important; &quot;&gt;TOTAL QUEBEC - EASTERN CANADA&lt;/th&gt;';
  echo &quot;&lt;th&gt;Amount&lt;br /&gt;Quantity&lt;/th&gt;&quot;;
  foreach($results as $r) {
      if($r-&gt;shipping_number == &quot;2326244&quot; OR $r-&gt;shipping_number == &quot;8451211&quot;){
          if($r-&gt;quarter == &quot;1&quot;){ echo &quot;&lt;td&gt;$r-&gt;cost $&lt;br /&gt;$r-&gt;qty&lt;/td&gt;&quot;; } else { echo &quot;&lt;td&gt;&amp;nbsp;&lt;/td&gt;&quot;; }
          if($r-&gt;quarter == &quot;2&quot;){ echo &quot;&lt;td&gt;$r-&gt;cost $&lt;br /&gt;$r-&gt;qty&lt;/td&gt;&quot;; } else { echo &quot;&lt;td&gt;&amp;nbsp;&lt;/td&gt;&quot;; }
          if($r-&gt;quarter == &quot;3&quot;){ echo &quot;&lt;td&gt;$r-&gt;cost $&lt;br /&gt;$r-&gt;qty&lt;/td&gt;&quot;; } else { echo &quot;&lt;td&gt;&amp;nbsp;&lt;/td&gt;&quot;; }
          if($r-&gt;quarter == &quot;4&quot;){ echo &quot;&lt;td&gt;$r-&gt;cost $&lt;br /&gt;$r-&gt;qty&lt;/td&gt;&quot;; } else { echo &quot;&lt;td&gt;&amp;nbsp;&lt;/td&gt;&quot;; }
      }
  }
  echo &quot;&lt;/tr&gt;&quot;;
  </code></pre>
  <p>Except that, obviously, the <code>foreach</code> loop goes through the results twice, resulting in not 4 cells being created but 8.</p>
  <h3>Sample results</h3>
  <p><img src="https://i.stack.imgur.com/SW5Gv.jpg" alt="Results" /></p>
  <h3>How the data is output right now</h3>
  <p><img src="https://i.stack.imgur.com/VPDYf.jpg" alt="Output" /></p>
  <h3>Question</h3>
  <p>How do I output this on a single line, so that the data is either queried and formatted in a way that makes sense to run it only through one loop (or how do I output a single row of data from multiple loops?)</p>
  <p>How would I do that?</p>
  <p>Keep in mind, I have multiple shipping_numbers (clients) that might apply for a single table, so I need all of their totals combined in a single result, except separated by quarters (months, and so on - but those are separate queries).</p>