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条)

报告相同问题?