dqqpf32897 2014-11-12 13:33
浏览 33
已采纳

PHP通过动态路径设置数组值

I am trying here to set the vale of the first child element of $map. I need to do this by referencing the path of the array i.e [0]['child'].

The function returns the path value ok if set but I am having trouble changing the value of that of that element. So in this case I want $map[0]['child'] to equal "new".

function getArrayPath($arr,$path) {

    foreach($path as $item){
    $arr = $arr[$item];
    }

    return $arr;
}


$map='[{"child":""},{"child":""},{"child":""}]';

$map=json_decode($map,true);

$path = array("0","child");

$target = getArrayPath($map,$path);

if($target==""){
$target="new";
}

var_dump($map);
  • 写回答

1条回答 默认 最新

  • dongtang1966 2014-11-12 13:44
    关注

    You can solve this by using references:

    function &getArrayPath(&$arr,$path) {
    //       ^--return     ^--receive
    //          reference     reference
        foreach($path as $item){
            $arr =& $arr[$item];
    //            ^--assign reference
        }
        return $arr;
    }
    
    
    $map = json_decode('[{"child":"1"},{"child":"2"},{"child":"3"}]', true);
    $path = array("0","child");
    
    $target =& getArrayPath($map,$path);
    //       ^--assign reference
    

    as you can see in this demo (your code slightly changed).

    Since PHP does not assign/return by reference as default, you always need to explicitly do that by adding the & operator.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用