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 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算