1

我写了一个数组包装类 PersonArray,它可以包含某种类型的对象(人)。每个人都有一个唯一的 getHash() 函数,它返回 ID + Name 作为唯一标识符。这允许从 PersonArray 中快速检索 Person。PersonArray 实际上包含两个内部数组。一种用于存储 Person 对象($items),另一种用于存储 Hash 值($itemsHash)。

我想创建一个 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() {}
}
4

1 回答 1

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);   
    }
}
于 2009-06-08T16:02:01.997 回答