dpgjci27392 2013-06-04 10:16
浏览 121
已采纳

两个具有相同值的数组键

Just wondering how I can easily have two array keys with the same associative value. My current code is:

$arraytest = array(
        'test1', 'test2' => 1,
        'test3', 'test4' => 2,
)

I want the array to work so the following code returns:

$arraytest['test1'] returns 1
$arraytest['test2'] returns 1

etc

thanks for your help, m

  • 写回答

4条回答 默认 最新

  • dousong1926 2013-06-04 10:23
    关注

    you can associate the reference of one variable to two array keys to simulate this situation :

    e.g.

    $a = 2;
    
    $arraytest = array (
      'test1' => &$a,
      'test2' => &$a
    );
    

    This way, as 'test1' and 'test2' point to $a in memory you will always have the value of the "real" $a using 'test1' and 'test2' of the array. However keep in mind using references in arrays should be avoided since this can lead to unexpected program behaviors:

    from php.net documentation

    "Note, however, that references inside arrays are potentially dangerous. Doing a normal (not by reference) assignment with a reference on the right side does not turn the left side into a reference, but references inside arrays are preserved in these normal assignments. This also applies to function calls where the array is passed by value."

    More details here => What References Do (php.net)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗