以循环方式传递数组引用不起作用?
在这种情况下,引用变量如何工作?当它以一种方式传递时,修改它是有效的。除了向您展示代码之外,我无法更好地解释它。
//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”为空时它可以工作,但当它不为空时它就不起作用......
How does a reference variable work in this case? Modifying it works when it's passed one way. I couldn't explain it better other than showing you the code.
//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;
}
It works when "one_2" is empty, but when it's not it doesn't...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你真的应该真的真的看看
array_walk_recursive ()
!You should really, really, really take a look at
array_walk_recursive()
!