我不确定我的记忆是否错误,但是当我上次使用PHP(多年前)时,我依旧记得做过这样的事情:
$firstVariable, $secondVariable = explode(' ', 'Foo Bar');
Run Code Online (Sandbox Code Playgroud)
请注意,上面的语法不正确,但在此示例中,它会将'Foo'分配给$ firstVariable,将'Bar'分配给$ secondVariable.
这个的正确语法是什么?
谢谢.
Jim*_* W. 54
list($firstVar, $secondVar) = explode(' ', 'Foo Bar');Run Code Online (Sandbox Code Playgroud)
list()就是你追求的目标.
Pet*_*tai 15
首先是list()的一些例子,然后是list()和explode()的2个例子.
基本上,您的列表可以是您想要的长度,但它是绝对列表.换句话说,数组中项目的顺序显然很重要,要跳过这些内容,您必须在列表中留下相应的空格().
最后,你不能列出字符串.
<?php
$info = array('coffee', 'brown', 'caffeine');
// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";
// Listing some of them
list($drink, , $power) = $info;
echo "$drink has $power.\n";
// Or let's skip to only the third one
list( , , $power) = $info;
echo "I need $power!\n";
// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar); // NULL
?>
Run Code Online (Sandbox Code Playgroud)
一些例子:
应用list(),explode()并Arrays以正常的关系:
<?php
// What they say.
list($firstVar, $secondVar, , , $thirdVar) = explode(' ', 'I love to hate you');
// What you hear.
// Disaplays: I love you
echo "$firstVar $secondVar $thirdVar";
?>
Run Code Online (Sandbox Code Playgroud)
最后,您可以将list()与数组结合使用.$VARIABLE[]将项目存储到数组的最后一个槽中.应该注意存储的订单,因为它可能与您期望的相反:
<?php
list(, $Var[], ,$Var[] , $Var[]) = explode(' ', 'I love to hate you');
// Displays:
// Array ( [0] => you [1] => hate [2] => love )
print_r($Var);
?>
Run Code Online (Sandbox Code Playgroud)
存储订单的原因的解释是在list()手册页的警告中给出的:
list() assigns the values starting with the right-most parameter. If you are
using plain variables, you don't have to worry about this. But if you are
using arrays with indices you usually expect the order of the indices in
the array the same you wrote in the list() from left to right; which it isn't.
It's assigned in the reverse order.
Run Code Online (Sandbox Code Playgroud)
从php7.1开始,您可以进行对称数组解构。
代码:(演示)
$array = [1,2,3];
[$a, $b, $c] = $array;
echo "$a $b $c";
// displays: 1 2 3
Run Code Online (Sandbox Code Playgroud)
不打电话list()。
有关深入的细分和示例,请看一下这篇文章:https : //sebastiandedeyne.com/the-list-function-and-practical-uses-of-array-destructuring-in-php/
对于使用explode()with list()或数组解构,如果不能保证一定数量的元素,则最佳做法是声明的第3个参数,explode()以确保赋值运算符的两面之间保持平衡。
[$firstVariable, $secondVariable] = explode(' ', $stringToBeHalved, 2);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26407 次 |
| 最近记录: |