php 如何将数组值转换为变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5786686/
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
How to turn array values into variables?
提问by user723220
I have two arrays. Like:
我有两个数组。喜欢:
Bear, prince, dog, Portugal, Bear, Clown, prince, ...
Bear, prince, dog, Portugal, Bear, Clown, prince, ...
and a second one:
第二个:
45, 67, 34, 89, ...
45, 67, 34, 89, ...
I want to turn the string keys in the first array into variables and set them equal to the numbers in the second array.
我想将第一个数组中的字符串键转换为变量并将它们设置为等于第二个数组中的数字。
Is it possible?
是否可以?
回答by deceze
extract(array_combine($arrayKeys, $arrayValues));
http://php.net/array_combine
http://php.net/manual/en/function.extract.php
http://php.net/array_combine
http://php.net/manual/en/function.extract.php
I'd recommend you keep the values in an array though, it's rarely a good idea to flood your namespace with variable variables.
不过,我建议您将值保留在数组中,用可变变量淹没命名空间很少是一个好主意。
回答by Mukesh Chapagain
Try using array_combine:-
尝试使用array_combine:-
<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);
print_r($c);
?>
Output:-
输出:-
Array (
[green] => avocado
[red] => apple
[yellow] => banana
)
Loop through this array and create variable for each key value:-
遍历此数组并为每个键值创建变量:-
foreach($c as $key => $value) {
$$key = $value;
}
Now, you can print the variables like:-
现在,您可以打印如下变量:-
echo $green." , ".$red." , ".$yellow;
Hope this helps. Thanks.
希望这可以帮助。谢谢。