Looping through array of different lengths in PHP -
i have order form inputs this:
<input type="text" name="booking[sandwich][roastbeef][qty]" /> <input type="text" name="booking[sandwich][cheese][qty]" /> <input type="text" name="booking[pizza][classic][qty]" /> <input type="text" name="booking[pizza][special][qty]" /> <input type="text" name="booking[coffee][qty]" />
i'm having trouble looping through arrays correctly.
here kind of output have:
<h2>sandwich</h2> <p><strong>roastbeef:</strong> 10</p> <p><strong>cheese:</strong> 5</p> <hr> <h2>coffee</h2> <p><strong>quantity:</strong> 15</p>
if pizza input empty, heading "pizza" should not printed! same "coffee" or "sandwich" group. if order not contain in group, heading should not printed.
i can't write specific tests every input, have 200 of them.
here have tried do:
$booking = $_post['booking']; //first check if there 1 or more input not empty if (!empty($booking)) { foreach ($booking $type => $items) { if (count(array_filter($items))) { $order .= "<hr>\n<h2>" . ucfirst($type) . ":</h2>\n"; } foreach ($items $name => $qty) { if ($qty > "0"){ $order .= "<p><strong>" . ucfirst($name) . ":</strong> " . $qty . "</p>\n"; } } } }
this code works when array has length of 2 keys. can't seem wrap brain around how deal other lengths. great!
edit:
with answer @treegarden, have need. need have sort of check if "group" empty, <h2>
should not printed. if (count(array_filter($entry)))
works in not printing thing if group empty, input have 2 keys.
if (!empty($booking)) { foreach($booking $key=>$entry) { if (count(array_filter($entry))) { echo "<h2>$key</h2>"; //should printed if 1 or more inputs in group not empty foreach($entry $key=>$subentry) { if(is_array($subentry) && $subentry['qty'] > 0) { echo "<p><strong>$key:</strong>" . $subentry['qty'] . "</p>"; } elseif(!is_array($subentry) && $subentry > 0) { echo "<p><strong>quantity:</strong> $subentry</p>"; } } echo '<hr/>'; } } }
maybe try recursion, example snippet:
<?php class recursivearrayonlyiterator extends recursivearrayiterator { public function haschildren() { return is_array($this->current()); } } ?>
else simple forward way assume have 3 or more nested loops, keep checking $value in $kv using is_array(), done invoking function.
Comments
Post a Comment