dtrt2368 2013-06-11 10:14
浏览 66
已采纳

更改递归数组的内部值

I would like to change the value of a recursive array.

One array provides the path to the variable to change:

$scopePath represents the path to change.

For example if $scopePath==Array("owners","products","categories")

and $tag="price";

I would like to change $value["owners"]["products"]["categories"]["tag"] to true

    $u=$value;
    foreach ($scopePath as $i => $s) {
        if (!isset($u[$s]))
            $u[$s]=Array();
        $u=$u[$s];
    }
    $u[$tag]=true;

I know the problem is because of the line $u=$u[$s] because this changes the reference to $u, but I don't know how to fix it.

  • 写回答

2条回答 默认 最新

  • doutu7123 2013-06-11 10:20
    关注

    Make $u referencing $value or an element inside $value.

    $u = &$value;
    foreach($scopePath as $i => $s) {
        if (!isset($u[$s]))
            $u[$s]=Array();
        $u = &$u[$s];
    }
    $u["tag"] = true;
    

    When $scopePath = array("owners","products","categories")

    print_r($value);
    

    will output

    Array
    (
        [owners] => Array
            (
                [products] => Array
                    (
                        [categories] => Array
                            (
                                [tag] => 1
                            )
                    )
            )
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度