配列をkeyにできる辞書書いた
Pythonの連想配列はタプルをkeyにできて色々便利そうだったのでPHPでも似たようなことができるようにした。
<?php class Dictionary implements IteratorAggregate { protected $dict = array(); function put($keyval, $value) { $key = $this->buildHash($keyval); $this->dict[$key] = $value; return $this; } function get($keyval, $defaultval = null) { $key = $this->buildHash($keyval); if (!isset($this->dict[$key])) return $defaultval; return $this->dict[$key]; } protected function buildHash($keyval) { if (is_array($keyval)) $keyval = $this->sortArray($keyval); return serialize($keyval); } function getIterator() { return new ArrayIterator(array_values($this->dict)); } protected function sortArray(Array $arr) { ksort($arr); foreach ($arr as $key => $val) if (is_array($val)) $arr[$key] = $this->sortArray($val); return $arr; } }
使い方
<?php $hoge = new Dictionary(); $hoge->put(array(), 'hoge'); $hoge->put(@array(id => 1, page => 2), 'fuga'); $hoge->put(@array(hoge, fuga, piyo), 'piyo'); $hoge->get(array()); //=>'hoge' $hoge->get(@array(page =>2, id => 1)); //=>'fuga' $hoge->get(@array(hoge, fuga, piyo)); //=>'piyo'