开发者

PHP use default array to keep live array structured correctly

I have an array holding some default settings for my plugin. As the plugin evolves settings maybe removed or added from version to version.

Here is an example default array:

$defaults = array(
                    'setting1' => 'somevalue',
                    'setting2' => 'somevalue',
                    'setting4' => 'somevalue',
  开发者_JAVA技巧                );

Here is an example of live settings data that the structure needs to be updated for the new $default structure:

$livesettings = array(
                        'setting1' => 'foo',
                        'setting2' => 'bar',
                        'setting3' => 'foobar',
                      );

I'm looking for a function where I can pass both arrays and the structure of the livesettings is updated to match the $defaults.

So in this case in livesettings:

  1. setting1 and setting2 isn't touched. Their values stay intact
  2. setting3 is removed as no longer needed
  3. setting4 is added with the default value of somevalue

Are their any functions in PHP that can do this in one go? If yes what is it? If no how would I achieve this with PHP code?


You want a combination of array_intersect_key() and array_merge().

$livesettings = array_intersect_key($livesettings, $defaults);
$livesettings = array_merge($defaults, $livesettings);

The first function will remove all keys not found in $defaults, while the second would add items from $defaults not found in $livesettings


you don't need to a function for this problam, you can also use the $defaults like a base array,

    $defaults = array(
                        'setting1' => 'somevalue',
                        'setting2' => 'somevalue',
                        'setting4' => 'somevalue',
                      );

    $livesettings = $defaults; // it will be copited by value,

    $livesettings['setting1']  = 'overriden setting 1';
    $livesettings['setting3'] = 'added new setting to live config';
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜