php: Array keys case *insensitive* lookup?

前端 未结 12 1980
予麋鹿
予麋鹿 2020-12-25 10:30
$myArray = array (\'SOmeKeyNAme\' => 7);  

I want $myArray[\'somekeyname\'] to return 7.
Is there a way to do this

12条回答
  •  半阙折子戏
    2020-12-25 11:19

    You could use ArrayAccess interface to create a class that works with array syntax.

    Example

    $lower_array_object = new CaseInsensitiveArray;
    $lower_array_object["thisISaKEY"] = "value";
    print $lower_array_object["THISisAkey"]; //prints "value"
    

    or

    $lower_array_object = new CaseInsensitiveArray(
        array( "SoMeThInG" => "anything", ... )
    );
    print $lower_array_object["something"]; //prints "anything"
    

    Class

    class CaseInsensitiveArray implements ArrayAccess
    {
        private $_container = array();
    
        public function __construct( Array $initial_array = array() ) {
            $this->_container = array_map( "strtolower", $initial_array );
        }
    
        public function offsetSet($offset, $value) {
            if( is_string( $offset ) ) $offset = strtolower($offset);
            if (is_null($offset)) {
                $this->container[] = $value;
            } else {
                $this->container[$offset] = $value;
            }
        }
    
        public function offsetExists($offset) {
            if( is_string( $offset ) ) $offset = strtolower($offset);
            return isset($this->_container[$offset]);
        }
    
        public function offsetUnset($offset) {
            if( is_string( $offset ) ) $offset = strtolower($offset);
            unset($this->container[$offset]);
        }
    
        public function offsetGet($offset) {
            if( is_string( $offset ) ) $offset = strtolower($offset);
            return isset($this->container[$offset])
                ? $this->container[$offset]
                : null;
        }
    }
    

提交回复
热议问题