How to access and manipulate multi-dimensional array by key names / path?

前端 未结 10 2200
北恋
北恋 2020-11-21 07:35

I\'ve to implement a setter in PHP, that allows me to specify the key, or sub key, of an array (the target), passing the name as a dot-separated-keys value.

10条回答
  •  粉色の甜心
    2020-11-21 07:47

    This is an approach using a static class. The benefits of this style is that your configuration will be globally accessible in your application.

    It works by taking in a key path for example "database.mysql.username" and splitting the string into each of the key parts and moving a pointer to create a nested array.

    The benefits of this approach is you can give a partial key and get back arrays of configuration values, you're not limited to just the end values. It also makes "default values" trivial to implement.

    If you would like to have multiple configuration stores, just remove the static keywords and use it as an object instead.

    Live Example

    class Config
    {
        private static $configStore = [];
        // This determines what separates the path
        // Examples: "." = 'example.path.value' or "/" = 'example/path/value'
        private static $separator = '.';
    
        public static function set($key, $value)
        {
            $keys = explode(self::$separator, $key);
    
            // Start at the root of the configuration array
            $pointer = &self::$configStore;
    
            foreach ($keys as $keySet) {
                // Check to see if a key exists, if it doesn't, set that key as an empty array
                if (!isset($pointer[$keySet])) {
                    $pointer[$keySet] = [];
                }
    
                // Set the pointer to the current key
                $pointer = &$pointer[$keySet];
            }
    
            // Because we kept changing the pointer in the loop above, the pointer should be sitting at our desired location
            $pointer = $value;
        }
    
        public static function get($key, $defaultValue = null)
        {
            $keys = explode(self::$separator, $key);
    
            // Start at the root of the configuration array
            $pointer = &self::$configStore;
    
            foreach ($keys as $keySet) {
                // If we don't have a key as a part of the path, we should return the default value (null)
                if (!isset($pointer[$keySet])) {
                    return $defaultValue;
                }
                $pointer = &$pointer[$keySet];
            }
    
            // Because we kept changing the pointer in the loop above, the pointer should be sitting at our desired location
            return $pointer;
        }
    }
    
    // Examples of how to use
    Config::set('database.mysql.username', 'exampleUsername');
    Config::set('database.mysql.password', 'examplePassword');
    Config::set('database.mysql.database', 'exampleDatabase');
    Config::set('database.mysql.host', 'exampleHost');
    
    // Get back all the database configuration keys
    var_dump(Config::get('database.mysql'));
    
    // Get back a particular key from the database configuration
    var_dump(Config::get('database.mysql.host'));
    
    // Get back a particular key from the database configuration with a default if it doesn't exist
    var_dump(Config::get('database.mysql.port', 3306));
    

提交回复
热议问题