我不确定我的记忆是否错误,但是当我上次使用PHP(多年前)时,我依旧记得做过这样的事情:
$firstVariable, $secondVariable = explode(' ', 'Foo Bar');
请注意,上面的语法不正确,但在此示例中,它会将'Foo'分配给$ firstVariable,将'Bar'分配给$ secondVariable。
这个的正确语法是什么?
感谢。
答案 0 :(得分:51)
list($firstVar, $secondVar) = explode(' ', 'Foo Bar');
list()就是你的目标。
答案 1 :(得分:15)
首先是仅使用list()的几个示例,然后是list()与explode()结合的2个示例。
PHP manual page for list()上的例子特别有启发性:
基本上,您的列表可以是您想要的长度,但它是绝对列表。换句话说,数组中项目的顺序显然很重要,要跳过这些内容,你必须在列表中留下相应的空格()。
最后,你不能列出字符串。
<?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
?>
一些例子:
将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";
?>
最后,您可以将list()与数组结合使用。 $VARIABLE[]
将项目存储到数组的最后一个插槽中。应该注意存储的订单,因为它可能与您期望的相反:
<?php
list(, $Var[], ,$Var[] , $Var[]) = explode(' ', 'I love to hate you');
// Displays:
// Array ( [0] => you [1] => hate [2] => love )
print_r($Var);
?>
列表()手册页上的警告中给出了存储订单的原因的解释:
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.
答案 2 :(得分:5)
从php7.1开始,你可以进行 Symmetric array destructuring 。
http://php.net/manual/en/migration71.new-features.php
代码:(Demo)
$array = [1,2,3];
[$a, $b, $c] = $array;
echo "$a $b $c";
// displays: 1 2 3
不调用list()
。
有关深入细分和示例,请仔细阅读此帖:https://sebastiandedeyne.com/posts/2017/the-list-function-and-practical-uses-of-array-destructuring-in-php