以循环的方式传递数组引用是行不通的


Passing the array reference in a loop manner doesn't work?

在这种情况下引用变量是如何工作的?当它单向传递时,修改它是有效的。除了给你看代码,我没有更好的解释了。

//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"为空时,它工作,但当它不是它不…

你真的,真的,真的应该看看array_walk_recursive() !