40

有没有办法从数组中引用数组键?这在代码格式中可能更有意义:

$array=array(
  "Key1"=>array(
    "Value1",
    "Value2"
  ),
  "Key2"=>&$this['Key1']
);

我想要的是$array['Key2']输出与$array['Key1']. 我可以在创建数组后添加$array['Key2']=&$array['Key1'];,但如果可能的话,我想将它全部保存在一个代码块中。

我已经检查了有关参考的文档,以及此处提出的一些类似问题以及搜索“php 数组参考”。

4

2 回答 2

31

事实证明,这个问题的答案是肯定的。然而,它不是一个整洁的语法,因为它使用了一种子语句,并且在当前范围内留下了一个额外的引用变量。

考虑以下代码:

<?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

  );

我很惊讶这没有错误,但确实如此 -这是证明。当然,你会这样做,但你可以......

于 2012-04-27T22:05:27.887 回答
1

不可能在一个块中完成,因为您还没有初始化变量。与类变量相同。要做到这一点,您将需要以任何方式创建任何变量,而不是仅使用其链接,而是使用内存,所以再一次,您的问题的真正答案是 - 不可能:)

于 2012-04-27T21:50:46.360 回答