"Quick and dirty" class to get an offset of multidimensional array by given path (sorry, that without comments).
classArrayAsPath{
protected$data= array(),$separator='.';
public function__construct(array$data= array()) {$this->data=$data;
}
public functionset($value,$path=null) {
if (!isset($path)) {$this->data=$value;
}$separator=$this->separator;$pathtoken=strtok($path,$separator);$code='';$pices='[\''.$pathtoken.'\']';
while ($pathtoken!==false) {
if (($pathtoken=strtok($separator)) !==false) {$code.='if (!isset($this->data'.$pices.')) $this->data'.$pices.' = array(); ';$pices.='[\''.$pathtoken.'\']';
} else {$code.='return $this->data'.$pices.' = $value;';
}
}
return eval($code);
}
public functionget($path='',$default=null) {$result=$this->data;$separator=$this->separator;$pathtoken=strtok($path,$separator);
while ($pathtoken!==false) {
if (!isset($result[$pathtoken]) ||is_string($result)) {
if (isset($default)) {
return$default;
}
throw newArrayAsPathException('Can\'t find "'.$pathtoken.'" in "'.$path.'"');
}$result=$result[$pathtoken];$pathtoken=strtok($separator);
}
return$result?$result:$default;
}
public functionhas($path) {$result=$this->data;$separator=$this->separator;$pathtoken=strtok($path,$separator);
while ($pathtoken!==false) {
if (!isset($result[$pathtoken]) ||is_string($result)) {
returnfalse;
}$result=$result[$pathtoken];$pathtoken=strtok($separator);
}
returntrue;
}
public functionsetSepatator($separator) {$this->separator=$separator;
}
public functiongetSeparator($separator) {
return$this->separator;
}
}?>
Code:
$params= newArrayAsPath;$params->set(array('foo'=> array('bar'=> array('item'=>'Value')
)
));
try {$params->set('test','foo.bar.far.new');printf('Array:
%s
foo.bar.item:
%s
foo.bar.far:
%s
foo.bar.far.new
%s',var_export($params->get(),true),var_export($params->get('foo.bar.item'),true),var_export($params->get('foo.bar.far'),true),var_export($params->get('foo.bar.far.new'),true)
);
} catch (ArrayAsPathException $e) {
echo'Oops! It seems that something is wrong. '.$e->getMessage();
}?>
Will display:
Array:
array (
'foo' =>
array (
'bar' =>
array (
'item' => 'Value',
'far' =>
array (
'new' => 'test',
),
),
),
)
foo.bar.item:
'Value'
foo.bar.far:
array (
'new' => 'test',
)
foo.bar.far.new:
'test'