dongyan5815 2014-02-05 10:35
浏览 49
已采纳

PHP - 丢失函数中的数组引用(本地到全局)

I made a small function to parse and get elements from a multidimensional array by a string written in a Unix-like path syntax.

function array_get($path, &$array) {
    $keys = preg_split('/[\/\\\]+/', $path, null, PREG_SPLIT_NO_EMPTY);
    $current = trim(array_shift($keys));
    if (is_array($array) && array_key_exists($current, $array)) {
        $path = implode("/", $keys);
        if (empty($path)) {
            // (Place the code here, see below)
            return $array[$current];
        }
        return array_get($path, $array[$current]);
    }
    return false;
}

So if I got a simple array like this

$arr = array(
    "A" => array(
        "X" => array(),
        "Y" => array(),
        "Z" => array()
    ),
    "B" => array(
        "X" => array(),
        "Y" => array(),
        "Z" => array()
    ),
    "C" => array(
        "X" => array(),
        "Y" => array(),
        "Z" => array()
    )
);

and I wish to fill it within some entries like these

$arr['A']['Z'][] = "foo";
$arr['A']['Z'][] = "bar";

I would do the same job using the following statements:

$var = array_get("A/Z", $arr);
$var[] = "foo";
$var[] = "bar";

But something went wrong.

If you try to run the code you will notice that going out of the local scope the references to the passed array will be lost.

If you wish to run a test, you can replace the placeholder comment line inside the function with these two code lines:

            $array[$current][] = "foo";
            $array[$current][] = "bar";

then you will see that the function would perform actually its own job.

Is there a way to maintain the references in output?

  • 写回答

2条回答 默认 最新

  • dpg78570 2014-02-05 10:44
    关注

    From the documentation, you can specify you want to return a reference by using the & character before the function name AND the function call.

    <?php
    
    function &foo(&$arr) {
      return $arr[0];
    }
    
    $a = [[]];
    $b = &foo($a);
    $b[0] = 'bar';
    print_r($a); /* outputs [ [ 'bar' ] ] */
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器