开发者

PHP: How to overwrite values in one array with values from another without adding new keys to the array?

I have an array with default settings, and one array with user-specified settings. I want to merge these two arrays so that the default settings gets overwritten with the user-specified ones.

I have tried to use array_merge, which does the overwriting like I want, but it also adds new settings if the user has specified settings that doesn't exist in the default ones. Is there a better function I can use for this than array_merge? Or is there a function I can use to filter the user-specified array so that it only contains keys that also exist in the default settings array?

Example of what I want

$default = array('a' => 1, 'b' => 2);
$user = array('b' => 3, 'c' => 4);

// Somehow merge $user into $default so we end up with this:
Array
(
    [a] => 1
    [开发者_开发技巧b] => 3
)


You can actually just add two arrays together ($user+$default) instead of using array_merge.

If you want to stop any user settings that don't exist in the defaults you can use array_intersect_key:

Returns an associative array containing all the entries of array1 which have keys that are present in all arguments

Example:

$default = array('a' => 1, 'b' => 2);
$user = array('b' => 3, 'c' => 4);

// add any settings from $default to $user, then select only the keys in both arrays
$settings = array_intersect_key($user + $default, $default);

print_r($settings);

Results:

Array
(
    [b] => 3
    [a] => 1
)

The keys/values (and order) are selected first from $user in the addition, which is why b comes before a in the array, there is no a in $user. Any keys not defined in $user that are defined in $default will then be added to the end of $user. Then you remove any keys in $user + $default that aren't defined in $default.


It's probably simplest to just loop over the keys in the default-settings array, if you only want to consider those. So you can do something like this:

foreach ($default_settings AS $key => $default_value)
{
    if (array_key_exists($key, $user_settings))
    {
        $combined_settings[$key] = $user_settings[$key];
    }
    else
    {
        $combined_settings[$key] = $default_value;
    }
}


foreach($default as $key=>$val){   
  if (isset($user[$key]))
  {
    $settings[$key] = $user[$key];
  } else {
    $settings[$key] = $default[$key];
  } 
}

I think this is what you want.


foreach($user_settings as $key=>$val){   
    $global_settings[$key] = $val; 
}

?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜