V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
adkudao
V2EX  ›  问与答

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

  •  
  •   adkudao · 2016-07-05 16:20:52 +08:00 · 1303 次点击
    这是一个创建于 3068 天前的主题,其中的信息可能已经有所发展或是发生改变。
    现在有这么一个函数, 可以批量传值, 生成列表, 格式如下:

    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'的字符串过去, 也跟上面的情况一样, 没办法生成列表



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

    搬运:


    Use

    ReflectionFunction::invokeArgs(array $args)
    or

    call_user_func_array( callback $callback, array $param_arr)
    adkudao
        3
    adkudao  
    OP
       2016-07-05 16:44:26 +08:00
    @500miles @BOYPT
    非常感谢楼上两位, 这就是我要的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5489 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 09:09 · PVG 17:09 · LAX 01:09 · JFK 04:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.