2013-10-26 77 views
0

我正在通過調用數組鍵的方式構建帶有定價的菜單。菜單顯示,但我無法獲取價格部分顯示的值。在函數內部聲明全局數組,但調用時不顯示值

我加載了一個關聯數組,並且正在從函數內部調用它的值。我聲明瞭全局作用域,並使用heredoc將值添加到表中。我也試圖通過封裝調用printMenu()函數。僅當代碼未放置在功能中時,價格才顯示在菜單內。

不知道這裏有什麼問題。請幫助!

printMenu(); 

    $plain = array(
     "small" => "3.50", 
     "medium" => "6.25", 
     "large" => "8.00" 
    ); 

    function printMenu() { 
     global $plain; 
     print <<<HERE 
     <table> 
      <tr> 
      <th>&nbsp;</th> 
      <th class = "pSize">Small</th> 
      <th class = "pSize">Med</th> 
      <th class = "pSize">Large</th> 
      </tr> 
      <tr> 
      <th>Plain</th> 
      <td class ="price">$plain[small]</td> 
      <td class ="price">$plain[medium]</td> 
      <td class ="price">$plain[large]</td> 
      </tr> 
     </table> 
    HERE; 
    } 

回答

1

你有你調用你的全局變量的函數之前聲明的變量:

$plain = array(
    "small" => "3.50", 
    "medium" => "6.25", 
    "large" => "8.00" 
); 

printMenu(); 

而且也許你會考慮到這個變量設置爲你的函數參數。選中這個:

function printMenu($argName) { 
    var_dump($argName); 
} 

$plain = array(
    "small" => "3.50", 
    "medium" => "6.25", 
    "large" => "8.00" 
); 

printMenu($plain); 
+0

我認爲它,但我有四個數組(即$ plain,$ vegetarian,$ pepperoni,$ hawaiian)。我只提供了一個數組作爲解決問題的辦法之一,應該是四個解決方案,輸入到一個表中。正確?並感謝你。首先回復我的其中一個帖子。我認爲我是一個信仰疊加的人,除了我無法贊成你的解決方案。希望能貢獻一個答案...有一天=/ –

+0

我不知道我是否能正確理解,但在文檔上查看'array_merge'。因爲你是新來的人,所以你不能贊成我的回答。目前,您只能在您的問題中檢查答案爲「已接受」。 – speccode

相關問題