字符串和数字作为数组键

3
如何创建键为数字和字符串的数组。
<?php
$array = array
(
    'test' => 'thing',
    'blah' => 'things'
);

echo $array[0]; // thing
echo $array[1]; // things

echo $array['test']; // thing
echo $array['blah']; // things
?>

你的问题不够清晰,你到底想要或者是指的是什么? - Sarfraz
那不可靠。关联数组中项的顺序不取决于输入的顺序。数组中的第一个元素可以是 blah ,也可以是 test - user253984
@dbemerlin:你有支持你评论的参考资料吗?我一直认为关联数组是按插入顺序排序的,但我在手册中找不到任何说明。 - grossvogel
3个回答

2
$array = array_values($array);

但为什么您需要那个呢?您能扩展一下您的例子吗?

我需要原始键,尝试为一个字符串键分配一个值,但我只有数字。 - NoOne

2
你可以使用array_keys来生成一个查找数组:
<?php
$array = array
(
    'test' => 'thing',
    'blah' => 'things'
);
$lookup = array_keys ($array);
// $lookup holds (0=>'test',1=>'blah)

echo $array[$lookup[0]]; // thing
echo $array[$lookup[1]]; // things

echo $array['test']; // thing
echo $array['blah']; // things
?>

1

你可以实现自己的类,它 "实现了 ArrayAccess 接口"

对于这样的类,你可以手动处理这样的行为

更新:只是出于好玩而已。

class MyArray implements ArrayAccess
{
    private $data;
    private $keys;

    public function __construct(array $data)
    {
        $this->data = $data;
        $this->keys = array_keys($data);
    }

    public function offsetGet($key)
    {
        if (is_int($key))
        {
            return $this->data[$this->keys[$key]];
        }

        return $this->data[$key];
    }

    public function offsetSet($key, $value)
    {
        throw new Exception('Not implemented');
    }

    public function offsetExists($key)
    {
        throw new Exception('Not implemented');
    }

    public function offsetUnset($key)
    {
        throw new Exception('Not implemented');
    }
}

$array = new MyArray(array(
    'test' => 'thing',
    'blah' => 'things'
));

var_dump($array[0]);
var_dump($array[1]);
var_dump($array['test']);
var_dump($array['blah']);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接