引用多维关联数组的值

时间:2012-04-30 14:05:54

标签: php recursion reference

我正在寻找一些棘手的事情:)

我有一个多维数组,如:

$array = array(
  "collection" => "departments",
  "action" => "find",
  "args" => array ("_id" => array("$in" => "{{variablename}}"))
);

我希望获得值{{variablename}}的引用,以便稍后更改它。 它必须是递归函数,因为我无法预测数组上{{variablename}}的位置。

没有递归没有probs,但我没有找到我能做到的。

PS:将数组转换为字符串或json并使用replace的其他解决方案对我不感兴趣。我真的需要参考。

1 个答案:

答案 0 :(得分:0)

不是很漂亮(也不是递归,这是一件好事),但应该有效:

// Input data
$array = array(
  "collection" => "departments",
  "action" => "find",
  "args" => array ("_id" => array('$in' => "{{variablename}}"))
);

// Create a stack
$stack = array(&$array);

// Loop until the stack is empty
while (sizeof($stack) > 0) {
    // Get the first variable in the stack (by reference)
    foreach ($stack as &$current) break;
    // Remove the first variable from the stack (by reference, same as array_shift but array_shift breaks the references) 
    $stack = array_slice($stack, 1);
    // If the shifted variable is an array
    if (is_array($current)) {
        // Add all the array's values to the stack (by reference)
        foreach ($current as &$value) {
            $stack[] =& $value;
        }
    } 
    // If the shifted variable is the one we want
    elseif ($current == '{{variablename}}') {
        // Stop the loop, leaving $current as the reference to the variable we want
        break;
    }
}
$current = 'test';
var_dump($current);
var_dump($array);

示例:http://ideone.com/hEzZk