合并“默认"具有“输入"的数组大批? PHP的哪个功能? [英] Merge "Defaults" array with "Input" array? PHP Which Function?

查看:85
本文介绍了合并“默认"具有“输入"的数组大批? PHP的哪个功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您正在让用户提供信息.

Array 1

但并非全部都是必需的.所以你有默认值.

Array 2

PHP是否具有根据Array 1中提供的值而不是空值来覆盖Array 2的所有数组值的功能?

解决方案

我认为您正在寻找的是array_replace_recursive,尤其是当您的默认值"可能是一个深度超过一个级别的关联数组时. /p>

$finalArray = array_replace_recursive(array $defaults, array $inputOptions)

这里是一个示例,该示例为函数使用可选的选项数组,并根据这些选项"opts"和您指定的defaults的结果进行一些处理:

function do_something() {
    $args = func_get_args();
            $opts = $args[0] ? $args[0] : array();

    $defaults = array(
        "second_level" => array(
                    "key1" => "val1",
                    "key2" => "val2"
                ),
        "key1" => "val1",
        "key2" =>  "val2",
        "key3" => "val3"
    );

    $params = array_replace_recursive($defaults, $opts);
    // do something with these merged parameters
}

php.net参考文档为此处

Lets say you are having a user provide information.

Array 1

But not all is required. So you have defaults.

Array 2

Does PHP have a function which will overwrite all array values of Array 2 based on if they are supplied in Array 1, and not empty?

解决方案

I think what you are looking for is array_replace_recursive, especially for the case when your "defualts" may be an associative array more than one level deep.

$finalArray = array_replace_recursive(array $defaults, array $inputOptions)

heres an example that takes an optional array of options to a function and does some processing based on the result of those options "opts" and the defaults which you specify:

function do_something() {
    $args = func_get_args();
            $opts = $args[0] ? $args[0] : array();

    $defaults = array(
        "second_level" => array(
                    "key1" => "val1",
                    "key2" => "val2"
                ),
        "key1" => "val1",
        "key2" =>  "val2",
        "key3" => "val3"
    );

    $params = array_replace_recursive($defaults, $opts);
    // do something with these merged parameters
}

The php.net reference document is here

这篇关于合并“默认"具有“输入"的数组大批? PHP的哪个功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆