简体   繁体   English

向关联数组添加维度

[英]Add a dimension to an associative array

I have an array of default settings, that needs to be an associative array, it allows me to merge it with an array of settings saved in database: 我有一个默认设置数组,它需要是一个关联数组,它允许我将其与数据库中保存的设置数组合并:

$defaults = array ( 'eswc_redirect' => false,
                    'eswc_remove_shop_title' => false,
                    'eswc_remove_footer_credits' => 'Yes',
                  );

I would like it to store more parameters for the same settings, not just its value, for example type that I will later use to properly sanitize all the settings in a loop. 我希望它为相同的设置存储更多的参数,而不仅仅是其值,例如,稍后将用于在循环中正确清除所有设置的类型。

I expect to have over 50 settings and I need to make it as simple as possible, without double or triple typing the same. 我希望有50多个设置,并且我需要使其尽可能简单,而无需两次或两次键入相同的内容。 I would like to have everything related to a single setting written in one line like this (I expect it not to work, it's just to show my intent): 我希望将与单个设置相关的所有内容写在这样的一行中(我希望它不起作用,这只是为了表明我的意图):

$defaults = array ( array ( 'eswc_redirect' => false, 'checkbox' ),
                    array ( 'eswc_remove_shop_title' => false, 'checkbox' ),
                    array ( 'eswc_remove_footer_credits' => 'Yes', 'text' ),
                  );

As a PHP novice, I would gladly see an example of how to access data from such an array in a loop. 作为PHP的新手,我很乐意看到一个示例,该示例演示如何循环访问此类数组中的数据。

I would also need to extract an array as presented in my 1st piece of code from this new array. 我还需要从这个新数组中提取出我的第一篇代码中介绍的数组。

it would be better to keep it as an associative array, but make the values nested associative arrays. 最好将其保留为关联数组,但使值嵌套关联数组。

$defaults = ['eswc_redirect' => ['value' => false, 'type' => 'checkbox' ],
             'eswc_remove_shop_title' => ['value' => false, 'type' => 'checkbox' ],
             'eswc_remove_footer_credits' => ['value' => 'Yes', 'type' => 'text' ],
    ];

Then you access it like $defaults['eswc_redirect']['value'] 然后像$defaults['eswc_redirect']['value']一样访问它

You can have many arrays in an array, for example: 数组中可以有多个数组,例如:

$defaults = [
    'settings' => [
        'eswc_redirect' => false,
        'eswc_remove_shop_title' => false,
        'eswc_remove_footer_credits' => 'Yes'
    ],
    'database_connection' => [
        'host' => 'localhost',
        'user' => 'root',
        'pass' => ''
    ]
];

And you can easily access each configuration, for example: 您可以轻松访问每个配置,例如:

$defaults['settings']['eswc_redirect']

and

$defaults['database_connection']['user']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM