Use Multidimensional Array within a For Loop in PHP
I have the following multidimensional array:
<? $array = array(0 => 2, 3 => 1, 5 => 1 );
Which looks like this when printed:
Array ( [0] => 2 [3] => 1 [5] => 1 ); //the value in brackets is the shoe size
The first part of array is a "shoe size", and the second part of the array is the number available in inventory.
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.
Here's what I have so far, but isn't working:
<?php
$array = array(0 => 2, 3 => 1, 5 => 1 );
print ('<table>');
print ('<thead><tr><开发者_C百科;th>Shoe Size</th>');
for ($i=3; $i<=12; $i += .50) {
print ('<th>'.$i.'</th>');
}
print('</tr></thead>');
print('<tbody><td>Total</td>');
foreach ($array as $shoe_size=>$number_in_inventory) {
for ($i=3; $i<=12; $i += .50) {
if ($i == $shoe_size) {
print('<td>'.$number_in_inventory.'</td>');
}
else {
print('<td>0</td>');
}
}
}
print("</tbody></table>");
My problem is, because I have a foreach
loop AND a for
loop, it is printing out twice the number of table columns (<td>
's).
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.
Many thanks!
Change your main loop to go through each possible shoe size; if the size exists in the inventory array ($array
) then print that value, else print zero.
// ...
print('<tbody><td>Total</td>');
for ($i = 3; $i <= 12; $i += .50) {
if (array_key_exists("$i", $array)) {
print '<td>'.$array["$i"].'</td>';
} else {
print '<td>0</td>';
}
}
// ...
My problem is, because I have a foreach loop AND a for loop, it is printing out twice the number of table columns ('s).
That is precisely the problem. Just like with the <th>
section, you want to print a <td>
for each of the possible shoe sizes (3 through 12). For each possible shoe size, all you need to do is check to see whether there is a corresponding value in the inventory as my snippet above does.
You might try looping through all the sizes and then for each size, check to see if it's in the array using array_key_exists()
精彩评论