将数组赋值给变量的PHP方法

39

我不确定我的记忆是否有误,但是当我上一次使用PHP(多年前)时,我依稀记得做过这样的事情:

$firstVariable, $secondVariable = explode(' ', 'Foo Bar');
请注意,上述代码是不正确的语法,但在此示例中,它会将“Foo”赋值给$firstVariable,“Bar”赋值给$secondVariable。
这个问题的正确语法是什么?
谢谢。
3个回答

69
list($firstVar, $secondVar) = explode(' ', 'Foo Bar');

list() 是你需要的。


25

从php7.1起,您可以使用对称数组解构

https://www.php.net/manual/en/migration71.new-features.php#migration71.new-features.symmetric-array-destructuring

代码:(演示)

$array = [1, 2, 3];
[$a, $b, $c] = $array;
echo "$a $b $c";
// displays: 1 2 3

不调用list()

在不声明临时变量的情况下,“交换”元素位置的新现代方法。请参见这里这里这里这里的示例。

有关详细说明和示例,请查看此帖子:https://sebastiandedeyne.com/the-list-function-and-practical-uses-of-array-destructuring-in-php/


如果您不能保证生成一定数量的元素,则使用explode()list()或数组解构的最佳实践是声明explode()的第三个参数以限制生成的元素数量。这不会强制产生太多元素;相反,它只会告诉php在达到那个元素数量时停止分裂。

[$firstVariable, $secondVariable] = explode(' ', $stringToBeHalved, 2);

如果您不确定您的分解数据是否会向赋值运算符另一侧提供平衡的数据,您可以使用上述技术实现最大值,并使用类似于 array_replace() 的东西在赋值运算符的右侧提供最少数量的元素。

代码: (演示)

$strings = [
    "1,2,3,4",
    "1,2,3",
    "1,2"
];

$minElements = 3;
$defElements = array_fill(0, $minElements, null);

foreach ($strings as $string) {
    [$a, $b, $c] = array_replace($defElements, explode(',', $string, $minElements));
    var_export($a);
    echo ' _ ';
    var_export($b);
    echo ' _ ';
    var_export($c);
    echo "\n-----------------\n";
}

输出:

'1' _ '2' _ '3,4'
-----------------
'1' _ '2' _ '3'
-----------------
'1' _ '2' _ NULL
-----------------

事实上,对称数组解构甚至允许多次访问同一元素/值-这可能会在第一眼看起来有点尴尬。

例如,您可以像这样将单个值推入两个数组:

[0 => $array1[], 0 => $array2[]] = ['zeroIndexedElement'];

阅读更多: 在解构数组时,是否可以多次访问相同的元素值?


还有一种很少建议使用的技术是调用extract()函数。如果您无法完全控制它正在处理的数据,则此函数可能很危险,因为它将所有数据的键推入全局作用域作为变量名,可能会覆盖变量并导致脚本存在漏洞或出错。

为了准备要提取的数据,请通过分配键来将索引数组转换为关联数组。

代码:(演示

$threeKeys = ['a', 'b', 'c'];
foreach ($strings as $string) {
    extract(array_combine($threeKeys, explode(',', $string, 3)));
    // now you can use $a, $b, and $c
}

上面的演示展示了在未提供平衡/预期数据量时生成的一些警告。所以,这个故事的寓意是要小心,通过确保数据处理器始终接收到所需数据来消除可能的边缘情况。


1
投票支持,让我们知道 PHP 7.1 中的这个新功能。 - Yassine Sedrani

20

首先是几个仅使用list()的例子,然后是两个与explode()结合使用的例子。


PHP手册页面上的示例特别有启发性:

基本上,您的列表可以任意长,但它是一个绝对列表。换句话说,数组中项目的顺序显然很重要,如果要跳过某些项目,则必须在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()手册页面的警告中给出:"

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.

list()不再按相反的顺序分配变量。http://php.net/manual/zh/migration70.incompatible.php#migration70.incompatible.variable-handling.list.order - German Khokhlov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接