Merge variables
We have $id
and $title
variables, which everytime change.
For each $id
we should create a new variable $temp_title_%id%
, and give to it $title
's value.
Like:
$id = 10;
$title = 'Hello people!';
$temp_title_10 = 'Hello people!';
Tryed this (doesn't work):
$temp_title_ . $id = $开发者_开发百科title;
Thanks.
How about using an array instead? An array is a much better way of storing multiple values. Much, much, much better.
$title_array = array();
$id = 10;
$title = 'Hello people!';
$title_array[$id] = $title;
If you're trying to persist your variables, it would probably be better to place them in an array if your $id
variable will always be an integer.
$persistence_array = array();
while (some_requirement) {
$id = ...;
$title = ...;
$persistence_array[$id] = $title;
}
If $id
might also contain alpha-numeric data, then you could always use a hash / dictionary in the same way (with a small amount of additional logic you could even store multiple values for the same id).
DON'T DO THIS: If you absolutely must have variables then you can use variable variables But please, don't.
Use this:
$metavariable = "temp_title_".$id;
$$metavariable = $title; // note the $$
${'temp_title_' . $id} = $title;
echo $temp_title_10;
I think it's a bad idea to do what you're trying to do, but here's how to do it anyways:
$GLOBALS["temp_title_".$id]=$title;
Alternatively, you could do this:
$varname="temp_title_".$id;
$$varname=$title;
The most correct way to do what I think you're trying to do would be to use an array:
// Somewhere in the PHP script:
$an_array=array();
// To assign:
$an_array[$id]=$title;
// To retrieve:
echo $an_array[$id];
Use variable variable of PHP http://php.net/manual/en/language.variables.variable.php
$variable = $title.'_'.$id
$$variable = 'hello, world!'
精彩评论