如何在给定任意数量的索引的情况下创建对嵌套在多维数组中的值的引用


How to create a reference to a value nested in a multidimensional array given an arbitrary amount of indexes

我有一个类,它与一个嵌套数组一起工作,我想对嵌套数组中的某个值执行操作,给定一组任意的索引。

我正在使用引用来引用正在被操作的值。

class Test {
    function __construct(){
       // just an example of a multi dimensional array to work with
       $this->data = array(
          array( 10, 100, 1000),
          array( 20, 200, 2000),
          array( 
               array( 30, 300, 3000), 
               array( 40, 400, 5000),
               array( 50, 400, 5000)
          )
       );
    }
    function set_reference( $indexes ){
        // set reference to a value somewhere inside $this->data
        $this->current = &$this->data[$not][$sure]; // but how
        return $this;
    }
    function add_three(){
        $this->current += 3;
        return $this;
    }
    function render(){
        var_dump( $this->current );
        return $this;
    }
}

这个例子将能够像这样工作:

$test = new Test();
$test->set_reference( array( 1, 1 ) )->add_three()->render(); // should show 203
$test->set_reference( array( 2, 1, 1 ) )->add_three()->render(); // should show 403

我正在努力解决这个问题,特别是因为似乎没有一种方便的方法来访问一个嵌套数组内的值给定一个可变数量的索引。我所得到的最接近的方法是使用eval,但是eval似乎不合适,并且不能在所有环境中工作,这是不可能的。

$indexes = "[2][1][1]"; // or "[1][1]" or "[0]" 
eval( 
    "if( isset( $this->data" . $indexes . " ) ) { 
        $this->current = &$this->data" . $indexes . ";
    }" 
);

我也试过用循环做一些事情来检索嵌套的值,但我不知道如何改变$this->current所指的值而不修改$this->data

使用循环遍历索引列表,在遍历过程中保留一个引用。

function set_reference( $indexes ){
    $current = &$this->data;
    foreach($indexes as $index) {
        $current = &$current[$index];
    }
    $this->current = &$current;
    return $this;
}

(如果您不希望以后对$this->current的修改影响$this->data,则删除& s)