编程语言
首页 > 编程语言> > 如何在PHP的数组中使用数组引用?

如何在PHP的数组中使用数组引用?

作者:互联网

我希望能够执行以下操作:

$normal_array       = array();
$array_of_arrayrefs = array( &$normal_array );

// Here I want to access the $normal_array reference **as a reference**,
// but that doesn't work obviously. How to do it?
end( $array_of_arrayrefs )["one"] = 1; // choking on this one

print $normal_array["one"]; // should output 1

问候

/ R

解决方法:

end()不会返回最后一个值的引用,而是最后一个值本身.这是一种解决方法:

$normal_array       = array();
$array_of_arrayrefs = array( &$normal_array );

$refArray = &end_byref( $array_of_arrayrefs );
$refArray["one"] = 1;

print $normal_array["one"]; // should output 1

function &end_byref( &$array ) {
    $lastKey = end(array_keys($array));
    end($array);
    return $array[$lastKey];
}

标签:reference,pass-by-reference,arrays,php
来源: https://codeday.me/bug/20191024/1922023.html