foreach ($data as $key => $value) {
echo $key; // let say cars
}
是否可以创建一个名为的新变量$cars
Are you looking for extract()
?
$data = array('thing' => 'ocean'
'size' => 'big'
'color' => 'blue');
extract($data);
echo "The $thing is $size and $color.";
The ocean is big and blue.
You can use foreach
and variable variables to do this:
foreach ($data as $key => $value)
{
$$key = $value;
}
But this doesn't offer the simplicity or the options of extract()
(eg: with extract()
, you can add a prefix, control how you want to deal with collisions, etc.)
是的:$key
包含"cars"
,echo $$key
将与:http echo $cars
: //php.net/manual/en/language.variables.variable.php相同
是的,可以使用变量 variables,如下所示:
$key = 'cars';
$$key = 'honda'; //$cars variable is created
echo $cars; //prints 'honda'
I think you're asking if it's possible to create a new variable that has the same name as the value of $key
- so 'cars'
would create $cars
, 'bikes'
would create $bikes
, etc?
Yes, this is possible, although it's generally not the best way to get things done.
$data = array(
'cars' => 7,
'bikes' => 3
);
foreach ($data as $key => $value) {
$$key = $value;
}
echo $cars; // 7
echo $bikes; // 3
$key 和 $value 变量不必称为 $key 和 $value。您可以根据需要重命名变量(以及任何有效的变量名称)。
foreach($data as $cars=>$model){
echo "$cars => $model";
}