2009-06-08 9 views
1

私は、特定の型(Person)のオブジェクトを含むことができる配列ラッパークラスPersonArrayを作成しました。すべての人は一意のIDとしてID + Nameを返すユニークなgetHash()関数を持っています。これにより、PersonArrayからPersonをすばやく取得できます。 PersonArrayは実際には2つの内部配列を保持します。 1つはPersonオブジェクト($ items)の格納用、もう1つはHash値($ itemsHash)の格納用です。PHP - ハッシュ配列、インデックスに挿入しますか?

Personオブジェクトを$ items配列の[index]位置に配置するinsertAt(index、Person)関数を作成します。 配列に特定の位置を挿入する方法はありますか?もしそうなら、どうすれば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とは何ですか?なぜあなたはそれらのハッシュによってインデックスをつけたままにして、$アイテムをすべてスキップできないのですか?どのように実際に反復を処理するクラスの外観は見えますか? Afaik Iteratorは単なるインタフェースです。このクラスとinsertAt関数の使い方のサンプルコードを表示できますか? (詳細、そしてなぜいくつかの機能は大文字で始まり、いくつかは始まっていないのですか?) – 0scar

答えて

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

+0

私はそうは思わない - http://pastebin.com/f6591bd6 –

関連する問題