我有一个关联数组,我可能需要通过数字访问(即获取第5个键的值)。数组访问关联值
$data = array(
'one' => 'something',
'two' => 'else',
'three' => 'completely'
) ;
我需要能够做到:
$data['one']
和
$data[0]
得到相同的值, '东西'。
我最初的想法是创建一个类包装与offsetGet(有代码,看看,关键是数字和采取相应的行动,用array_values实现了ArrayAccess):
class MixedArray implements ArrayAccess {
protected $_array = array();
public function __construct($data) {
$this->_array = $data;
}
public function offsetExists($offset) {
return isset($this->_array[$offset]);
}
public function offsetGet($offset) {
if (is_numeric($offset) || !isset($this->_array[$offset])) {
$values = array_values($this->_array) ;
if (!isset($values[$offset])) {
return false ;
}
return $values[$offset] ;
}
return $this->_array[$offset];
}
public function offsetSet($offset, $value) {
return $this->_array[$offset] = $value;
}
public function offsetUnset($offset) {
unset($this->_array[$offset]);
}
}
我想知道是否有ISN”任何内置的方式在PHP中这样做。我宁愿使用本地功能,但到目前为止,我还没有看到任何这样做。
任何想法?
谢谢
FANIS
我刚刚意识到自从我问了以后我就没有更新过它。 我最终使用了我在问题中编写的内容,但稍微进行了优化,以便在首次使用array_values()查找数字索引之后,将数字索引保留在类变量中。 – Fanis 2010-08-12 10:26:52