2009-07-13 125 views
1

我有一个关联数组,我可能需要通过数字访问(即获取第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

+0

我刚刚意识到自从我问了以后我就没有更新过它。 我最终使用了我在问题中编写的内容,但稍微进行了优化,以便在首次使用array_values()查找数字索引之后,将数字索引保留在类变量中。 – Fanis 2010-08-12 10:26:52

回答

0

我注意到你提到它是一个只读数据库的结果集

如果你正在使用MySQL,那么你可以做这样的事情

$result = mysql_query($sql); 
$data = mysql_fetch_array($result); 

mysql_fetch_array返回与两个关联和数字键

数组

http://nz.php.net/manual/en/function.mysql-fetch-array.php

+0

啊,非常好。我已经忘记了这一点。我正在使用PEAR :: DB,但似乎没有公开的这样的选项。我想我可以直接进入PEAR/DB/mysql。php :: fetchInto()并将其更改为使用MYSQL_BOTH,但我宁愿不要这样破解它:) 不过,您给了我一些想法,谢谢 – Fanis 2009-07-13 09:21:16

4
how about this 

$data = array(
    'one' => 'something', 
    'two' => 'else', 
    'three' => 'completely' 
) ; 

then 
$keys = array_keys($data); 

Then 
$key = $keys[$index_you_want]; 

Then 
echo $data[$key]; 
+0

对,但事先并不知道我是否会做数字或关联。我需要同时为其他人使用我的数组包装器。 – Fanis 2009-07-13 08:00:53

+0

它应该适用于两者。 – TigerTiger 2009-07-13 08:04:45

1

没有内置的方式做到这一点。

如果这是一个一次性的事情,你可以使用类似:

$array = array_merge($array, array_values($array)); 

当你添加新的项目到阵列虽然这不会更新。

+0

这是非常readonly(数据库结果集),所以我认为这可以工作。但是,它会消耗更多的记忆,这在大集合中可能是不需要的。 最后我会记住它,因为它可能只是小套装的最快方式,而不是在它上面有两层包装纸 – Fanis 2009-07-13 08:02:57

0

有时更容易检查您是否有关联密钥或n index with is_int()

if(is_int($key)) 
    return current(array_slice($data, $key, 1)); 
else 
    return $data[$key];