在这种情况下,参考变量如何工作?修改它在单向传递时有效。除了向你展示代码之外,我无法更好地解释它。
//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”为空时它起作用,但是当它不是时它会起作用......