php 数组没有定义_PHP: array - Manual

"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'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值