我有一个关联数组,我可能需要访问数字(即获得第5键的值)。

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

我需要能够做到:

$data['one']

$data[0]

要得到相同的值, '东西'。

我最初的想法是创建一个类包装与offsetGet(具有代码实现了ArrayAccess),看看是否关键是数字和采取相应的行动,利用array_values:

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]);
    }    

}

我想知道如果没有任何内置的方式在PHP中做到这一点。我宁愿使用本机的功能,但到目前为止,我还没有看到任何这一点。

任何想法?

谢谢,结果 FANIS

有帮助吗?

解决方案

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

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

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

mysql_fetch_array返回一个数组与两个缔合和数字键

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

其他提示

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];

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

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

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

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

有时更容易检查,如果你有一个关联键或is_int()指数

if(is_int($key))
    return current(array_slice($data, $key, 1));
else
    return $data[$key];
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top