我写了一个数组包装类PersonArray,它可以包含某种类型的对象(Person)。每个人都有一个独特的getHash()函数,它将ID + Name作为唯一标识符返回。这允许从PersonArray中快速检索Person。 PersonArray实际上拥有两个内部数组。一个用于存储Person对象($ items),另一个用于存储Hash值($ itemsHash)。PHP - 散列数组,插入索引?
我想创建一个insertAt(index,Person)函数,将Person对象放在$ items数组的[index]位置。 有没有办法将一个数组中的某个位置插入?如果是的话,我怎样才能更新PersonArray的$ itemsHash?
class Person {
function getHash() {
return $this->id . $this->name;
}
}
class PersonArray implements Iterator {
public $items = array();
public $itemsHash = array();
public function Find($pKey) {
if($this->ContainsKey($pKey)) {
return $this->Item($this->internalRegisteredHashList[$pKey]);
}
}
public function Add($object) {
if($object->getHash()) {
$this->internalRegisteredHashList[$object->getHash()] = $this->Count();
array_push($this->items, $object);
}
}
public function getItems() {
return $this->items;
}
function ContainsKey($pKey) {}
function Count() {}
function Item($pKey) {}
//Iteration implementation
public function rewind() {}
public function current() {}
public function key() {}
public function next() {}
public function valid() {}
}
问题:我没有完全掌握你的情况。这堂课完成了吗?什么是internalRegisteredHashList?为什么你不能让它们通过哈希索引并跳过$ items?该类如何看待实际处理迭代? Afaik Iterator只是一个界面,对吧?你能展示一些你想如何使用这个类和insertAt函数的示例代码吗? (细节,为什么有些函数以大写字母开头,有些则不是?) – 0scar 2009-06-08 16:14:12