php 用键名但空值初始化关联数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12880026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:25:17  来源:igfitidea点击:

Initialize an Associative Array with Key Names but Empty Values

phparraysinitializationassociative

提问by NYCBilly

I cannot find any examples, in books or on the web, describing how one would properly initialize an associative array by name only (with empty values) - unless, of course, this IS the proper way(?)

我在书籍或网络上找不到任何示例来描述如何仅按名称(使用空值)正确初始化关联数组 - 当然,除非这是正确的方法(?)

It just feels as though there is another more efficient way to do this:

感觉好像还有另一种更有效的方法来做到这一点:

config.php

配置文件

class config {
    public static $database = array (
        'dbdriver' => '',
        'dbhost' => '',
        'dbname' => '',
        'dbuser' => '',
        'dbpass' => ''
    );
}

// Is this the right way to initialize an Associative Array with blank values?
// I know it works fine, but it just seems ... longer than necessary.

index.php

索引.php

require config.php

config::$database['dbdriver'] = 'mysql';
config::$database['dbhost'] = 'localhost';
config::$database['dbname'] = 'test_database';
config::$database['dbuser'] = 'testing';
config::$database['dbpass'] = 'P@$$w0rd';

// This code is irrelevant, only to show that the above array NEEDS to have Key
// names, but Values that will be filled in by a user via a form, or whatever.

Any recommendations, suggestions, or direction would be appreciated. Thanks.

任何建议、建议或方向将不胜感激。谢谢。

回答by GolezTrol

What you have is the most clear option.

你拥有的是最明确的选择。

But you could shorten it using array_fill_keys, like this:

但是您可以使用array_fill_keys缩短它,如下所示:

$database = array_fill_keys(
  array('dbdriver', 'dbhost', 'dbname', 'dbuser', 'dbpass'), '');

But if the user has to fill the values anyway, you can just leave the array empty, and just provide the example code in index.php. The keys will automatically be added when you assign a value.

但是如果用户无论如何都必须填充值,您可以将数组留空,并在 index.php 中提供示例代码。当您分配值时,键将自动添加。

回答by Seth

First file:

第一个文件:

class config {
    public static $database = array();
}

Other file:

其他文件:

config::$database = array(
    'driver' => 'mysql',
    'dbhost' => 'localhost',
    'dbname' => 'test_database',
    'dbuser' => 'testing',
    'dbpass' => 'P@$$w0rd'
);