向关联数组添加维度

时间:2019-07-10 22:58:54

标签: php

我有一个默认设置数组,它需要是一个关联数组,它允许我将其与数据库中保存的设置数组合并:

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

我希望它为相同的设置存储更多的参数,而不仅仅是它的值,例如,稍后将用于在循环中正确清除所有设置的类型。

我希望有50多个设置,我需要使其尽可能简单,而不能两次或三次键入相同的内容。我希望将与单个设置相关的所有内容写在这样的一行中(我希望它不起作用,只是为了表明我的意图):

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

作为一个PHP新手,我很乐意看到一个示例,该示例演示如何循环访问此类数组中的数据。

我还需要从这个新数组中提取我的第一段代码中显示的数组。

2 个答案:

答案 0 :(得分:1)

最好将其保留为关联数组,但将值嵌套在关联数组中。

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

然后您像$defaults['eswc_redirect']['value']

一样访问它

答案 1 :(得分:0)

一个数组中可以有多个数组,例如:

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

您可以轻松访问每个配置,例如:

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

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