2017-08-04 55 views
1

我有在PHP多維數組鍵,下面的代碼:功能,如多維數組

<?php 

    $weather = array (
     "AVAILABLE" => array (
      "first" => "We're having a nice day.", 
      "second" => "We're not having a nice day.", 
      "fifth" => "It's raining out there.", 
      "tenth" => "It's gonna be warm today.")); 

    function getDomain() { 
     if (strpos($_SERVER['SERVER_NAME'], '.com') !== FALSE) { 
      return "first"; 
     } 
     elseif (strpos($_SERVER['SERVER_NAME'], '.eu') !== FALSE) { 
      return "second"; 
     } 
     else { 
      die(); 
     } 
    } 

    function myWeather($string) { 
     $domain = getDomain(); 
     return $weather[$string][$domain]; 
    } 

    echo myWeather("AVAILABLE"); 

?> 

當我在與域名.com網站,應該呼應的鍵值「可用」在域名鍵(「第一」) - 我們有一個愉快的一天。

當我在網站上使用域名.eu時,它應該寫入關鍵字「AVAILABLE」的值,但是在另一個域名關鍵字(「第二個」)中 - 我們沒有愉快的一天。

我該如何做這項工作?稍後將會有更多的鍵$weather

+2

'myWeather'無法看到'$ weather'數組,因爲它定義在函數範圍之外 – billyonecan

回答

2

需要添加陣列作爲參數給函數myWeather(): -

<?php 

$weather = array (
       "AVAILABLE" => array (
        "first" => "We're having a nice day.", 
        "second" => "We're not having a nice day.", 
        "fifth" => "It's raining out there.", 
        "tenth" => "It's gonna be warm today." 
       ) 
      ); 

function getDomain() { 
    if (strpos($_SERVER['SERVER_NAME'], '.com') !== FALSE) { 
     return "first"; 
    } 
    elseif (strpos($_SERVER['SERVER_NAME'], '.eu') !== FALSE) { 
     return "second"; 
    } 
    else { 
     return "fifth"; // instead of die(); return some value 
    } 
} 

function myWeather($string,$array) { 
    $domain = getDomain(); 
    return $array[$string][$domain]; 
} 

echo myWeather("AVAILABLE",$weather); 

?> 

注: - 上述需要做出陣列可用內部功能範圍

工作輸出: - https://eval.in/841524