2009-06-08 72 views
1

我寫了一個數組包裝類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() {} 
} 
+0

問題:我沒有完全掌握你的情況。這堂課完成了嗎?什麼是internalRegisteredHashList?爲什麼你不能讓它們通過哈希索引並跳過$ items?該類如何看待實際處理迭代? Afaik Iterator只是一個界面,對吧?你能展示一些你想如何使用這個類和insertAt函數的示例代碼嗎? (細節,爲什麼有些函數以大寫字母開頭,有些則不是?) – 0scar 2009-06-08 16:14:12

回答

1

你會發現它是更快和更容易使用PHP的關聯數組,而不是重新實現它們。

順便說一句,如果實際上只是迭代數組,則還可以實現更簡單的IteratorAggregate

例如

class PersonArray implements IteratorAggregate { 
    public $items = array(); 

    public function getItems() { 
     return $this->items; 
    } 

    public function Add($object) { 
     if($object->getHash()) { 
      $this->items[$object->getHash()] = $object; 
     } 
    } 

    public function Find($pKey) { 
     if(isset($this->items[$pKey])) { 
      return $this->items[$pKey]; 
     } 
    } 

    public function insertAt($index, $person) { 
     $tmp = array_slice($this->items, 0, $index); 
     $tmp[$person->getHash()] = $person; 
     $tmp = array_merge($tmp, array_slice($this->items, $index)); 

     $this->items = $tmp; 
    } 

    //IteratorAggregate implementation 
    public function getIterator() { 
     return new ArrayIterator($this->items); 
    } 
} 
+0

但是性能如何?不是foreach()通過關聯數組比較慢,然後遍歷索引數組? – Ropstah 2009-06-08 16:41:08