PHP 将数组赋值给变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3340750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:24:07  来源:igfitidea点击:

PHP Assign array to variables

phparrayslist

提问by TomBBB

I'm not sure if my memory is wrong, but when I last used PHP (years ago), I vaguely remember doing something like this:

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

$firstVariable, $secondVariable = explode(' ', 'Foo Bar');

Note that the above is incorrect syntax, however in this example it would assign 'Foo' to $firstVariable, and 'Bar' to $secondVariable.

请注意,上面的语法是错误的,但是在本例中,它会将 'Foo' 分配给 $firstVariable,将 'Bar' 分配给 $secondVariable。

What is the correct syntax for this?

什么是正确的语法?

Thanks.

谢谢。

回答by Jim W.

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

list()is what you are after.

list()是你所追求的。

回答by Peter Ajtai

First a few examples with list() alone, then 2 examples with list() combined with explode().

首先是几个单独使用 list() 的示例,然后是两个将 list() 与explode() 结合使用的示例。



The examples on the PHP manual page for list()are especially illuminating:

PHP 手册页上的 list()示例特别有启发性:

Basically, your list can be as long as you want, but it is an absolute list. In other words the order of the items in the array obviously matters, and to skip things, you have to leave the corresponding spots empty in your list().

基本上,您的列表可以任意长,但它是一个绝对列表。换句话说,数组中项目的顺序显然很重要,要跳过某些内容,您必须将 list() 中的相应位置留空。

Finally, you can't list string.

最后,你不能列出字符串。

<?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

?>


A few cases by example:

举几个例子:

Applying list(), explode()and Arraysto dysfunctional relationships:

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";
?>

Finally, you can use list() in conjunction with arrays. $VARIABLE[]stores an item into the last slot in an array. The order things are stored should be noted, since it's probably the reverse of what you expect:

最后,您可以将 list() 与数组结合使用。$VARIABLE[]将项目存储到数组的最后一个槽中。应该注意存储的顺序,因为它可能与您期望的相反:

<?php
list(, $Var[], ,$Var[] , $Var[]) = explode(' ', 'I love to hate you');
// Displays: 
// Array ( [0] => you [1] => hate [2] => love )
print_r($Var);
?>

The explanation of why the order things are stored in is as it is is given in the warning on the list() manual page:

对事物存储顺序的解释与 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.

回答by mickmackusa

From php7.1, you can do Symmetric array destructuring.

从 php7.1 开始,您可以进行对称数组解构

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

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

Code: (Demo)

代码:(演示

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

Without calling list().

无需调用list()

For in-depth breakdown and examples, have a long look at this post: https://sebastiandedeyne.com/the-list-function-and-practical-uses-of-array-destructuring-in-php/

有关深入的细分和示例,请长时间查看这篇文章:https: //sebastiandedeyne.com/the-list-function-and-practical-uses-of-array-destructuring-in-php/



As for using explode()with list()or array destructuring, if you are not guaranteed a certain number of elements, it is best practice to declare the 3rd parameter of explode()to limit the number of generated elements. This will not force the production of so many elements; rather it will merely tell php to stop exploding when that number of elements is achieved.

至于使用explode()withlist()或数组解构,如果不能保证一定数量的元素,最好的做法是声明第三个参数 ofexplode()来限制生成元素的数量。这不会强制生产这么多元素;相反,它只会告诉 php 在达到该数量的元素时停止爆炸。

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

If you aren't 100% assured that your exploded data will provide balanced data to the other side of the assignment operator, you can implement a maximum with the technique above and use something akin to array_replace()to provide a minimum number of elements on the right side of the assignment operator.

如果您不能 100% 保证分解数据将为赋值运算符的另一侧提供平衡数据,则可以使用上述技术实现最大值,并使用类似于array_replace()在右侧提供最少元素数量的方法赋值运算符。

Code: (Demo)

代码:(演示

$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";
}

Output:

输出:

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


And one more technique that is very seldom advised is to call extract(). This function can be dangerous if you don't have complete control of the data that it is processing because it will push all of the data's keys into the global scope as variable names -- potentially overwriting variables and leading to script vulnerability or breakage.

另一种很少被推荐的技术是调用extract(). 如果您无法完全控制正在处理的数据,则此函数可能会很危险,因为它会将所有数据的键作为变量名推送到全局范围内——可能会覆盖变量并导致脚本漏洞或损坏。

To prepare the data for extraction, convert indexed the array into an associative array by assigning keys.

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

Code: (Demo)

代码:(演示

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

The above demo shows some of the Warnings generated when not providing balanced/expected volumes of data. So the moral of this story is to be careful and eliminate possible fringe cases by ensuring the data processors will always receive what they require.

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