我想在 php 中执行解构,就像下面的 javascript 代码一样:
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(a,b,rest);
Run Code Online (Sandbox Code Playgroud)
输出:
10 20 [ 30, 40, 50 ]
Run Code Online (Sandbox Code Playgroud)
我如何在 php 中执行该操作?
我的 PHP 代码是:
<?php
$array = [10, 20, 30, 40, 50];
// Using the list syntax:
//list($a, $b, $c[]) = $array;
// Or the shorthand syntax:
[$a, $b, $c[]] = $array;
echo "$a<br>$b<br>";
print_r ($c);
?>
Run Code Online (Sandbox Code Playgroud)
哪个打印:
10
20
Array ( [0] => 30 )
Run Code Online (Sandbox Code Playgroud)
但我想要 $c 中的“[ 30, 40, 50 ]”
想知道是否有可能像func_get_args()(引用)那样进行调用而不是产生0索引数组,导致关联数组,使用变量名作为键?
例如:
function foo($arg1, $arg2)
{
var_dump(func_get_args());
}
foo('bar1', 'bar2');
// Output
array(2) {
[0]=>
string(4) "bar1"
[1]=>
string(4) "bar2"
}
// Preferred
array(2) {
[arg1]=>
string(4) "bar1"
[arg2]=>
string(4) "bar2"
}
Run Code Online (Sandbox Code Playgroud)
我问的原因是,我需要验证这些args作为数组传递给RPC函数,实际上是填充的.而且似乎最好是具体内容而不是希望它们以正确的顺序传递:
// Now
if (array_key_exists(0, $args)) {
// Preferred
if (array_key_exists('arg1', $args)) {
Run Code Online (Sandbox Code Playgroud)
在传递给RPC之前,我很容易从传入原始函数的args创建一个assoc数组,但只是想知道是否有一个已编译的函数为我做这个.
谢谢.
- 编辑 -
对不起,我忘了提到我触摸的代码已经存在,这意味着我无法更改功能签名.