1

我正在寻找一个有点棘手的东西:)

我有一个多维数组,例如:

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

我想引用值 {{variablename}} 以便以后更改它。它必须是一个递归函数,因为我无法预测 {{variablename}} 在数组上的位置。

没有递归就没有问题,但是我没有找到如何做到这一点。

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

4

1 回答 1

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

于 2012-04-30T14:15:37.303 回答