Note that there are some explanatory texts on larger screens.

plurals
  1. POUse Multidimensional Array within a For Loop in PHP
    primarykey
    data
    text
    <p>I have the following multidimensional array:</p> <pre><code>&lt;? $array = array(0 =&gt; 2, 3 =&gt; 1, 5 =&gt; 1 ); </code></pre> <p>Which looks like this when printed:</p> <pre><code>Array ( [0] =&gt; 2 [3] =&gt; 1 [5] =&gt; 1 ); //the value in brackets is the shoe size </code></pre> <p>The first part of array is a "shoe size", and the second part of the array is the number available in inventory.</p> <p>I am trying to print out a table that lists all shoe sizes (even if not in the array), and then loop through to provide "number available" in inventory.</p> <p>Here's what I have so far, but <strong>isn't working</strong>:</p> <pre><code>&lt;?php $array = array(0 =&gt; 2, 3 =&gt; 1, 5 =&gt; 1 ); print ('&lt;table&gt;'); print ('&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Shoe Size&lt;/th&gt;'); for ($i=3; $i&lt;=12; $i += .50) { print ('&lt;th&gt;'.$i.'&lt;/th&gt;'); } print('&lt;/tr&gt;&lt;/thead&gt;'); print('&lt;tbody&gt;&lt;td&gt;Total&lt;/td&gt;'); foreach ($array as $shoe_size=&gt;$number_in_inventory) { for ($i=3; $i&lt;=12; $i += .50) { if ($i == $shoe_size) { print('&lt;td&gt;'.$number_in_inventory.'&lt;/td&gt;'); } else { print('&lt;td&gt;0&lt;/td&gt;'); } } } print("&lt;/tbody&gt;&lt;/table&gt;"); </code></pre> <p>My problem is, because I have a <code>foreach</code> loop <strong>AND</strong> a <code>for</code> loop, it is printing out <strong>twice the number</strong> of table columns (<code>&lt;td&gt;</code>'s).</p> <p>How can I better adjust this code so that it only loops through and correctly displays the columns once? I am pretty lost on this one.</p> <p>Many thanks! </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload