有没有一种方法可以从数组中引用数组键?这可能在代码格式中更有意义:
$array=array(
"Key1"=>array(
"Value1",
"Value2"
),
"Key2"=>&$this['Key1']
);
Run Code Online (Sandbox Code Playgroud)
我想要的是$array['Key2']
输出相同的$array['Key1']
.我可以$array['Key2']=&$array['Key1'];
在创建数组后添加,但是如果可能的话,我希望将它全部保存在一个代码块中.
我已经检查了文档中的参考文献,以及一些建议类似的问题,并搜索"php数组引用".
Dav*_*dom 29
事实证明,答案是肯定的.然而,它不是一个整洁的语法,因为它使用一种子语句,并使当前范围散落着额外的引用变量.
请考虑以下代码:
<?php
$array = array(
// Creates Key1 and assigns the value to it
// A copy of the value is also placed in $ref
// At this stage, it's not a reference
"Key1"=>($ref = array(
"Value1",
"Value2"
)),
// Now Key2 is a reference to $ref, but not to Key1
"Key2"=>&$ref,
// Now everything is referenced together
"Key1"=>&$ref
);
Run Code Online (Sandbox Code Playgroud)
我很惊讶这种方法没有错误,但确实如此 - 这就是证据.当然,你不会这样做,但你可以......