[英]How to store each array value in a variable with PHP
I have an array that looks something like this: 我有一个看起来像这样的数组:
Array
(
[2] => http://www.marleenvanlook.be/admin.php
[4] => http://www.marleenvanlook.be/checklogin.php
[5] => http://www.marleenvanlook.be/checkupload.php
[6] => http://www.marleenvanlook.be/contact.php
)
What I want to do is store each value from this array to a variable (using PHP). 我想做的是将每个数组中的值存储到变量中(使用PHP)。 So for example: 因此,例如:
$something1 = "http://www.marleenvanlook.be/admin.php";
$something2 = "http://www.marleenvanlook.be/checklogin.php";
...
You can use extract()
: 您可以使用extract()
:
$data = array(
'something1',
'something2',
'something3',
);
extract($data, EXTR_PREFIX_ALL, 'var');
echo $var0; //Output something1
More info on http://br2.php.net/manual/en/function.extract.php 有关http://br2.php.net/manual/en/function.extract.php的更多信息
Well.. you could do something like this? 恩..你可以做这样的事情吗?
$myArray = array("http://www.marleenvanlook.be/admin.php","http://www.marleenvanlook.be/checklogin.php","etc");
$i = 0;
foreach($myArray as $value){
${'something'.$i} = $value;
$i++;
}
echo $something0; //http://www.marleenvanlook.be/admin.php
This would dynamically create variables with names like $something0
, $something1
, etc holding a value of the array assigned in the foreach
. 这将动态创建名称$something0
, $something1
等的变量,这些变量持有在foreach
分配的数组的值。
If you want the keys to be involved you can also do this: 如果您希望包含密钥,也可以执行以下操作:
$myArray = array(1 => "http://www.marleenvanlook.be/admin.php","http://www.marleenvanlook.be/checklogin.php","etc");
foreach($myArray as $key => $value){
${'something'.$key} = $value;
}
echo $something1; //http://www.marleenvanlook.be/admin.php
PHP has something called variable variables which lets you name a variable with the value of another variable. PHP具有称为变量变量的名称,它使您可以使用另一个变量的值来命名变量。
$something = array(
'http://www.marleenvanlook.be/admin.php',
'http://www.marleenvanlook.be/checklogin.php',
'http://www.marleenvanlook.be/checkupload.php',
'http://www.marleenvanlook.be/contact.php',
);
foreach($something as $key => $value) {
$key = 'something' . $key;
$$key = $value;
// OR (condensed version)
// ${"something{$key}"} = $value;
}
echo $something2;
// http://www.marleenvanlook.be/checkupload.php
But the question is why would you want to do this? 但问题是为什么您要这样做? Arrays are meant to be accessed by keys, so you can just do: 数组可以通过键访问,因此您可以执行以下操作:
echo $something[2];
// http://www.marleenvanlook.be/checkupload.php
What I would do is: 我要做的是:
$something1 = $the_array[2];
$something2 = $the_array[4];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.