Problems encountered in real development: How to pass each element of the array as an actual parameter of the variable parameter function?
Multiple pieces of data are found from MySQL, which is an array result set, eg: ['Zhang San','Li Si', 'foo', 'bar']
;
Need to be The result set is written to the SET
type of Redis
; the PHP operation class library of
Redis provides the sAdd()
method. The usage examples are as follows:
Usage examples:
$redis->sAdd('key1' , 'member1'); /* 1, 'key1' => {'member1'} */ $redis->sAdd('key1' , 'member2', 'member3'); /* 2, 'key1' => {'member1', 'member2', 'member3'}*/ $redis->sAdd('key1' , 'member2'); /* 0, 'key1' => {'member1', 'member2', 'member3'}*/
because sAdd()
is a variable parameter method, so the question is:
How can we use the above ['Zhang San', 'Li Si', 'foo', 'bar']
like this $redis->sAdd ('key1', 'Zhang San', 'Li Si', 'foo', 'bar');
instead of using it in a loop as follows:
$redis->multi(); foreach(['张三','李四', 'foo', 'bar'] as $value) { $redis->sAdd('key1', $value); } $redis->exec();
Real development problems: How to use arrays Each element is passed in as an argument to a variadic function?
Multiple pieces of data are found from MySQL, which is an array result set, eg: ['Zhang San','Li Si', 'foo', 'bar']
;
The results need to be Sets are written to the SET
type of Redis
; the PHP operation class library of
Redis provides the sAdd()
method. The usage examples are as follows:
Usage examples:
$redis->sAdd('key1' , 'member1'); /* 1, 'key1' => {'member1'} */ $redis->sAdd('key1' , 'member2', 'member3'); /* 2, 'key1' => {'member1', 'member2', 'member3'}*/ $redis->sAdd('key1' , 'member2'); /* 0, 'key1' => {'member1', 'member2', 'member3'}*/
because sAdd()
is a variable parameter method, so the question is:
How can we use the above ['Zhang San','Li Si', 'foo', 'bar']
like this$redis->sAdd( 'key1', 'Zhang San', 'Li Si', 'foo', 'bar');
instead of using it in a loop as follows:
$redis->multi(); foreach(['张三','李四', 'foo', 'bar'] as $value) { $redis->sAdd('key1', $value); } $redis->exec();
call_user_func_array $redis->multi();foreach(['张三','李四', 'foo', 'bar'] as $key=>$value) { $redis->sAdd('key'.$key, $value); }$redis->exec();
The above is how PHP uses each element of the array as a variable parameter function Actual parameters passed in? For more related content, please pay attention to the PHP Chinese website (www.php.cn)!
Related articles:
The difference between JS and PHP in passing variable parameters to functions Example code