简体   繁体   English

PHP array_walk_recursive:两种方法,结果不同

[英]PHP array_walk_recursive: two approaches, different result

Given the following setup: 给定以下设置:

    $storer = array();
    $arr = array(1, 2, 3);

I'm curious why this does not write to $storer ... 我很好奇为什么这不写到$storer ...

array_walk_recursive($arr, function($val, $key) {
    global $storer;
    $storer[] = 'foo';
});
print_r($storer); //no change - empty

..but this does: ..但是这样做:

array_walk_recursive($arr, function($val, $key) use (&$storer) {
    $storer[] = 'foo';
});
print_r($storer); //three items, all 'foo'

Can anyone enlighten me? 谁能启发我? In a user function I would expect global to provide read/write access. 在用户函数中,我希望global变量提供读/写访问权限。

After pulling my hair out trying to get a flattened array with keys this works: 将我的头发拔出后,尝试使用键获取一个扁平数组,这可行:

$result = array();

array_walk_recursive($inputarray,function($v, $k) use (&$result){ $result[$k] = $v;  });

$inputarray = $result;

I hope someone finds this and it helps. 我希望有人能找到它并有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM