我寫了一個數組包裝類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