2015-05-12 54 views
3

我有這樣的輸入的順序形式:通過不同長度的陣列循環在PHP

<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]" /> 

我無法通過陣列循環正確。

這裏是我想有什麼樣的輸出:

<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> 

如果所有的比薩輸入是空的,標題爲「比薩」應該不會被顯示出來!與「咖啡」或「三明治」組相同。如果訂單不包含組中的任何內容,則不應打印標題。

我不能爲每個輸入寫特定的測試,因爲我有200個輸入。

這是我試圖做:當陣列有兩個密鑰的長度

$booking = $_POST['booking']; 

//First check if there is one or more input that is not empty 
if (!empty($booking)) { 

    foreach ($booking as $type => $items) { 
    if (count(array_filter($items))) { 
     $order .= "<hr>\n<h2>" . ucfirst($type) . ":</h2>\n"; 
    } 
    foreach ($items as $name => $qty) { 
     if ($qty > "0"){ 
      $order .= "<p><strong>" . ucfirst($name) . ":</strong> " . $qty . "</p>\n"; 
     } 
    } 
    } 
} 

此代碼纔有效。我似乎無法將我的大腦包裹在如何處理其他長度。任何幫助將是偉大的!

編輯︰

從@treegarden的答案,我幾乎我所需要的。現在我只需要進行一些檢查,如果「組」是空的,那麼不應該打印<h2>if (count(array_filter($entry)))工作在不打印任何東西,如果組是空的,但僅適用於那些只有兩個鍵的輸入。

if (!empty($booking)) { 

    foreach($booking as $key=>$entry) { 
     if (count(array_filter($entry))) { 

      echo "<h2>$key</h2>"; //Should only be printed if one or more inputs in the group are not empty 

      foreach($entry as $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/>'; 
     } 
    }   


} 
+0

如果您知道哪個'items'只有一個鍵(咖啡爲例),你可以有這些項目的數組:'$ noItemsArr =陣列(「咖啡」,... );'然後,在條件中使用'in_array()'來使用第二個'foreach'或不使用''。聽起來不錯? –

+0

我有200個輸入,並且爲每個只有一個鍵的陣列編寫特定的測試會是很多工作。 –

回答

0

也許嘗試recursion,從例如片段:

<?php 
class RecursiveArrayOnlyIterator extends RecursiveArrayIterator { 
    public function hasChildren() { 
    return is_array($this->current()); 
    } 
} 
?> 

其他簡單的前進方式是假設你有三個或更多的嵌套循環, 繼續檢查是利用is_array()在$千伏$值,這是通過調用一個函數完成的。

0

試試這個

$booking = $_POST['booking']; 

if (!empty($booking)) { 

    foreach ($booking as $type => $items) { 
    if (count(array_filter($items))) { 
     $order .= "<hr>\n<h2>" . ucfirst($type) . ":</h2>\n"; 
    } 
    foreach ($items as $name => $qty) { 
     if (is_array($qty)) { 
      foreach ($qty as $qt) { 
      if ($qty > "0"){ 
      $order .= "<p><strong>" . ucfirst($name) . ":</strong> " . $qt. "</p>\n"; 
      } 
     } 
     } else { 
     if ($qty > "0"){ 
      $order .= "<p><strong>" . ucfirst($name) . ":</strong> " . $qty . "</p>\n"; 
     } 
     } 
    } 
    } 
} 
+0

啊!幾乎完美!即使是空的,烤牛肉也會印上。 –

+0

然後只需添加一個條件來檢查qty是否大於0. –

+0

是檢查使用是空方法 – Prasad