views:

319

answers:

1

Hi,

i wrote an array wrapper class PersonArray which can contain objects of a certain type (Person). Every person has a unique getHash() function which returns the ID + Name as a unique identifier. This allows for speedy retrieval of the Person from the PersonArray. The PersonArray actually holds two internal Arrays. One for the storage of Person objects ($items), and one for the storage of the Hash values ($itemsHash).

I want to create a insertAt(index, Person) function which puts the Person object at the [index] position in the $items array. Is there a way to insertAt a certain position in an array? If so how can I also update the $itemsHash of the PersonArray?

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() {}
}
+1  A: 

You may find it is faster and easier to use PHP's associative arrays rather than re-implementing them.

As an aside you can also implement the simpler IteratorAggregate if you are actually just iterating over an array.

e.g.

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);   
    }
}
Tom Haigh
But how about performance? Isn't foreach() over an associative-array slower then looping over an indexed-array?
Ropstah
I don't think so - http://pastebin.com/f6591bd6
Tom Haigh