功能,如多维数组

问题描述:

我有在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

需要添加阵列作为参数给函数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