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

时间:2014-05-17 06:25:08

标签: php arrays multidimensional-array

我有一个使用嵌套数组的类,我希望在给定一组任意索引的情况下对该嵌套数组中的某个值执行操作。

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

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引用的值。

1 个答案:

答案 0 :(得分:1)

使用循环遍历索引列表,随时保留引用。

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

(如果您不希望以后修改$this->current影响$this->data,请删除&