如何获取数组';s引用,使其成为标量以用作数组键,并使其返回到PHP中的引用


How to get an array's reference, make it scalar to use as an array key and make it back to a reference in PHP?

我需要引用一个数组,并以某种方式使其成为标量,这样它就可以成为另一个数组的键
散列应该是可逆的,也就是说,再次将其转换为操作原始数组的引用
这可能吗?

示例:

<?php
$a = [1,2,3];
$b = hash_reference( $a );
$c = [$b => 'hi']; // this is legal because $b is a scalar
$d = unhash_reference( $b );
// here $d is a reference to $a just like if: $d = &$a

理论上是可能的,但我怀疑你需要这样做的原因。

简单地说,字符串是一种可以用作数组键的标量类型——你可以只使用json_encode($a)并将其用作数组键吗?json的用法很糟糕,但在您所述的示例问题中起作用。

可以说,您最好用某种形式的类来包装这个需求。在这样做的过程中,您可以将某种形式的uniqid()与所讨论的数组进行匹配。

我构建了这个粗糙的例子,这样至少你不会使用变量或其他全局范围。

class LookupTable {
    protected $data = [];
    public function store($x) { 
        $id = uniqid();
        $this->data[$id] = $x;
        return $id;
    }
    public function retrieve($id) {
        return $this->data[$id];
    }
}
$t = new LookupTable();
$a = [1,2,3];
$b = $t->store($a);
$c = [$b => 'hi'];
$d = $t->retrieve($b);
$r = &$a;
var_dump($a === $d); // is it the same object.
var_dump($a === $r); // its still the same object.
var_dump($c); // scalar array index! woohoo!
var_dump($d); // hey look, same object! :)