加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php按路径选择数组

发布时间:2020-12-13 17:25:51 所属栏目:PHP教程 来源:网络整理
导读:我可以帮忙知道这是否可行? 我想动态选择数组. 例如, $oj = (object)['A' = (object)['B' = (object)['C' = (object)['D' = []]]]]$E = 'A'$oj-$E // this will work$E = 'A-B' $oj-$E // this will not work 除了写一个完整的路径,我还能做什么?或者也许
我可以帮忙知道这是否可行?

我想动态选择数组.

例如,

$oj = (object)['A' => (object)['B' => (object)['C' => (object)['D' => []]]]]

$E = 'A'
$oj->$E // this will work

$E = 'A->B'  
$oj->$E // this will not work

除了写一个完整的路径,我还能做什么?或者也许请告诉我这是否可行或是否有任何我可以参考的例子?

$oj[A][B][C][D]     <---NO
$oj->A->B->C->D     <---NO

$E = A->B->C->D    
$oj->E              <--What I want   


Question Update: 

$oj->E = 'Store something'  <-What I want,then will store into $oj.

//So E here is not pick up the value of D,but the path of D;

非常感谢你.

解决方法

您可以通过 – >爆炸路径并通过路径的一部分跟踪对象部分:

function getPath($obj,$path) {
  foreach(explode('->',$path) as $part) $obj = $obj->$part;
  return $obj;
}

$oj = (object)['A' => (object)['B' => (object)['C' => (object)['D' => []]]]];
$E = 'A->B->C->D';
getPath($oj,$E);

如果你也想写,你可以做到丑陋,但使用eval的简单方法:

eval("$tgt=&$oj->$E;"); // $tgt is the adress of $oj->A->B->C->D->E
print_r($tgt); // original value of $oj->A->B->C->D->E
$tgt = "foo"; 
print_r($oj); // $oj->A->B->C->D->E = "foo"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读