Zai*_*lek 5 php arrays destructuring variable-declaration spread-syntax
我想在 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 ]”
我使用展开运算符和函数做到了这一点:
function f1($a,$b,...$c) {
return ['a' => $a, 'b' => $b, 'c' => $c];
}
$array = [10, 20, 30, 40, 50];
extract (f1(...$array));
echo "$a<br>$b<br>";
print_r ($c);
Run Code Online (Sandbox Code Playgroud)
请告诉我这是否是正确的方法。