2009-06-08 80 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