【问题标题】:Function as a key in multidimensional array [duplicate]作为多维数组中的键的功能[重复]
【发布时间】:2018-01-12 07:45:31
【问题描述】:

我在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 访问网络时,它应该在域键(“first”)中回显键“AVAILABLE”的值 - 我们度过了愉快的一天。

当我使用域 .eu 进入站点时,它应该写入键“AVAILABLE”的值,但在另一个域键(“第二”)中 - 我们今天过得不好。

请问我怎样才能完成这项工作?以后数组$weather会有更多的key。

【问题讨论】:

  • myWeather 看不到 $weather 数组,因为它是在函数范围之外定义的

标签: php arrays variables multidimensional-array


【解决方案1】:

需要将数组作为参数添加到函数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

【讨论】:

    猜你喜欢
    • 2018-11-09
    • 2013-09-18
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 2011-10-22
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    相关资源
    最近更新 更多