以循环方式传递数组引用不起作用?

时间:2011-10-18 18:45:20

标签: php reference

在这种情况下,参考变量如何工作?修改它在单向传递时有效。除了向你展示代码之外,我无法更好地解释它。

//this is the haystack and the array to be modified
$data = array(
    'one_1' => array('value' => ''), 
    'one_2' => array('value' => ''), 
    'one_3' => array('value' => '')
);

// index to search for
$needle = 'one_2';

// value to assign to
$value = 'awesome';

// start haystack modification
modify_arr($data, $needle, $value);

// this function forms the reference to the needle in the haystack e.g $data['one_2']
function modify_arr(&$ref, $index, $value) {
    $res = $ref;
    foreach ($ref as $key => $arr) {
        if(is_array($arr)) 
            $res[$key] = modify_arr($arr, $index, $value);
        if ($key == $index)
            write_values($ref, $key, $value);
    }
    // assign back the modified copy of $ref
    $ref = $res;
    return 
}

function write_values(&$ref, $key, $value) { 
    if (empty($ref[$key]['value']) || !$ref[$key]['value']) {
        // assign the value when value is empty
        $ref[$key]['value'] = $value;
    } else {
        // if it's not empty, increment the needle's suffix to form a new needle and assign to it instead
        // result would be: from "one_1" to "one_2" 
        $key_parts = split_key($key);
        $new_key = $key_parts[0] . '_' . ((int)$key_parts[1] + 1); // result is "one_2" 
        return modify_arr($ref, $new_key, $value);
    } 
    return;
}

当“one_2”为空时它起作用,但是当它不是时它会起作用......

1 个答案:

答案 0 :(得分:2)

你真的,真的,真的要看看array_walk_recursive()