PHP - 变量变量和变量array_merge() - 不工作
我有一堆数组,它们存储在不同的变量中,例如 $required、$reserved 等...
我想允许(在函数内部)传递一个选项数组(例如 $options = array ('required', 'reserved')
),然后该数组将用于定义哪些数组要合并在一起并在函数末尾返回。
因此,我在函数的一部分中有这段代码,它应该获取所有选项并合并数组,使用变量变量从选项数组中传递的字符串中获取数组):
$array = array();
foreach ($options as $key) {
$array_to_merge = ${$key};
array_merge($array, $array_to_merge);
}
return $array;
但是,当我返回 $array 时,它显示 0 项。如果我 print_r($array_to_merge);
,我实际上会得到整个数组。
array_merge() 根本不适用于可变变量,还是我在这里遗漏了一些东西......?
I have a bunch of arrays, which are stored in different variables like $required, $reserved, etc...
I would like to allow (inside a function) an array of options to be passed (like $options = array('required', 'reserved')
), and that array would then be used to define which arrays to merge together and return at the end of the function.
So, I have this code in part of the function, that should grab all the options and merge the arrays, using variable variables to get the arrays from the strings passed in the options array):
$array = array();
foreach ($options as $key) {
$array_to_merge = ${$key};
array_merge($array, $array_to_merge);
}
return $array;
However, when I return the $array, it shows 0 items. If I print_r($array_to_merge);
, I actually get the entire array as I should.
Does array_merge() simply not work with variable variables, or am I missing something here...?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
array_merge 返回合并的数组,您没有将该返回值分配给任何内容,因此它会丢失。
应该可以解决你的问题。
array_merge returns the merged array, you're not assigning that return value to anything and thus it is being lost.
should fix your problem.
如果我没看错,您还可以将代码简化为:
compact
替换变量变量查找并获取数组列表。实际上,只需要一次array_merge
调用。If I read it right you can also simplify your code (replaces the loop) to just:
compact
replaces the variable variable lookup and gets the list of arrays. And in effect there is only onearray_merge
call necessary.