PHP数组键可以有别名吗?

Nin*_*aKC 6 php arrays alias

这只是一个奇怪的问题,背后的推理纯粹是为了让我更加懒惰.这就是我的意思..

说我有一个网站,在那里的htaccess让漂亮的网址,并把数据发送到$ _GET ["P"]数组键为当前页面".在索引文件中,我设置了页面,我要做的第一件事是在配置文件$ _PAGE数组中设置一些页面设置.现在,假设我有多个页面,我想要具有相同的设置,(在页面中,其他东西可能会稍微改变,与设置不对应.所以目前,我有一些看起来像以下2个php文件.

// index.php
include('page.array.php');

echo '<title>'.$_PAGE[$_GET['p']]['title'].'</title>';

// page.array.php
$_PAGE = array(
    'some/page/' => array(
        'title' => 'This is an example'
    )
)
$_PAGE['some/aliased/page/'] = $_PAGE['some/page/'];
Run Code Online (Sandbox Code Playgroud)

请注意,在页面数组的末尾,为了"别名"页面,我必须在创建数组后将其添加到结尾.

在PHP中是否有任何方法可能我只是不知道,这可能会让我有点懒惰(同时添加到更干净的代码),并使它,所以我可以简单别名的密钥?我注意到以下内容不起作用,我想我的问题是,有没有办法在创建数组期间在同一个数组中创建别名?

这个例子不起作用:

// page.array.php
$_PAGE = array(
    'some/page/' => array(
        'title' => 'This is an example'
    ),
    'some/aliased/page/' => $_PAGE['some/page/']
)
Run Code Online (Sandbox Code Playgroud)

也许是一种从内部引用"this"数组的方法?

如果无法做到这一点,我对"不可能"的答案没有疑问.虽然如果你有更好的方法来解决这个问题,除了我上面描述的方式,为了更懒惰,我会有兴趣阅读它:)

Sam*_*son 2

我不相信您可以拥有像这样镜像数组中其他值的数组值。不过,首先想到的是$_PAGEswitch语句中构建数组,使用失败值作为别名:

// Define path for testing, and empty page array
$path = "some/aliased/page";
$page = Array();

// Time to evaluate our path
switch ($path) {
    // If it's either of these two cases
    case "some/page":
    case "some/aliased/page":
        // Assign this array to $page
        $page = Array("Title" => "Two Paths, One Page.");
        break;
    // If it's this case
    case "some/other/path":
        // Assign this array to $page
        $page = Array("Title" => "Something else.");
        break;
    // If the path isn't found, default data
    default:
        $page = Array("Title" => "Page not found");
}

// Output the result
var_dump($page);
Run Code Online (Sandbox Code Playgroud)

执行它:http://sandbox.onlinephpfunctions...ebd3dee1f37c5612c25