简体   繁体   English

PHP - 变量变量 & array_merge() - 不工作

[英]PHP - Variable Variables & array_merge() - not working

I have a bunch of arrays, which are stored in different variables like $required, $reserved, etc...我有一堆 arrays,它们存储在不同的变量中,如 $required、$reserved 等...

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.我想允许(在函数内部)传递一个选项数组(例如$options = array('required', 'reserved') ),然后该数组将用于定义哪个 arrays 合并在一起并返回在 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):因此,我在 function 的一部分中有此代码,它应该获取所有选项并合并 arrays,使用变量变量从选项数组中传递的字符串中获取 arrays:

$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.但是,当我返回 $array 时,它显示 0 个项目。 If I print_r($array_to_merge);如果我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...? array_merge() 是否根本不适用于变量变量,或者我在这里遗漏了什么......?

array_merge returns the merged array, you're not assigning that return value to anything and thus it is being lost. array_merge 返回合并的数组,您没有将该返回值分配给任何东西,因此它正在丢失。

$array = array_merge($array, $array_to_merge);

should fix your problem.应该解决你的问题。

If I read it right you can also simplify your code (replaces the loop) to just:如果我没看错,您还可以将代码(替换循环)简化为:

 $array = call_user_func_array("array_merge", compact($options));

compact replaces the variable variable lookup and gets the list of arrays. compact替换变量变量查找并获取 arrays 的列表。 And in effect there is only one array_merge call necessary.实际上,只需要一个array_merge调用。

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

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