-1
foreach ($data as $key => $value) {
    echo $key; // let say cars
}

是否可以创建一个名为的新变量$cars

4

5 回答 5

2

Are you looking for extract()?

$data = array('thing' => 'ocean'
              'size' => 'big'
              'color' => 'blue');

extract($data);

echo "The $thing is $size and $color.";

Prints:

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.)

于 2012-10-18T22:39:22.413 回答
1

是的:$key包含"cars"echo $$key将与:http echo $cars: //php.net/manual/en/language.variables.variable.php相同

于 2012-10-18T22:33:45.047 回答
1

是的,可以使用变量 variables,如下所示:

$key = 'cars';
$$key = 'honda'; //$cars variable is created
echo $cars; //prints 'honda'
于 2012-10-18T22:34:22.063 回答
0

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
于 2012-10-18T22:37:14.680 回答
-1

$key 和 $value 变量不必称为 $key 和 $value。您可以根据需要重命名变量(以及任何有效的变量名称)。

foreach($data as $cars=>$model){
    echo "$cars => $model";
}
于 2012-10-18T22:33:38.287 回答