请教一个很尴尬的 PHP 语法问题:如何在批量传值?

2016-07-05 16:20:52 +08:00
 adkudao
现在有这么一个函数, 可以批量传值, 生成列表, 格式如下:

rpush( 键名, 键值 1, 键值 2... )



比如这样是可以的:
--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
$redis -> rpush('test', '1', '2', '3');
--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---

这样能在 redis 中生成一个一维数组列表[1, 2, 3]



但是这样就不行:
--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
$haomas = range(1, 3);

foreach ($haomas as $key => $value)
{
$str .= ','. $value;
}

$redis -> rpush('test', substr($str, 1));
--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---

这样会把 1,2,3 合并成'1, 2,3' 作为一个字符串统一传过去, 变成了一个普通的关系键: test => '1, 2, 3' , 而不是列表



然后这样也不行:
--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
$haomas = range(1, 3);
$redis -> rpush('test', $haomas);
--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
这样会传一个'Array'的字符串过去, 也跟上面的情况一样, 没办法生成列表



请问如何批量把值传递给函数呢? 谢谢大家了
1302 次点击
所在节点    问与答
3 条回复
500miles
2016-07-05 16:25:35 +08:00
call_user_func_array([$redis, 'rpush'], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
BOYPT
2016-07-05 16:29:27 +08:00
google: php use array as argument list

搬运:


Use

ReflectionFunction::invokeArgs(array $args)
or

call_user_func_array( callback $callback, array $param_arr)
adkudao
2016-07-05 16:44:26 +08:00
@500miles @BOYPT
非常感谢楼上两位, 这就是我要的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/290430

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX