php字符串名称作为变量

时间:2011-01-11 10:30:22

标签: php


$string = "id";

want result to be like 

$id = "new value";

我如何在php中编码?

编辑..

下面怎么样?


$column = array("id","name","value");

let say found 3 row from mysql

want result to be like this

$id[0] = "3";
$id[1] = "6";
$id[2] = "10";

$name[0] = "a";
$name[1] = "b";
$name[2] = "c";

$value[0] = "bat";
$value[1] = "rat";
$value[2] = "cat";


8 个答案:

答案 0 :(得分:8)

Theres 2主要方法

第一个是双$Variable Variable),如此

$var = "hello";
$$var = "world";
echo $hello; //world

//You can even add more Dollar Signs

$Bar = "a";
$Foo = "Bar";
$World = "Foo";
$Hello = "World";
$a = "Hello";

$a; //Returns Hello
$$a; //Returns World
$$$a; //Returns Foo
$$$$a; //Returns Bar
$$$$$a; //Returns a

$$$$$$a; //Returns Hello
$$$$$$$a; //Returns World

//... and so on ...//

@source

第二种方法是使用{}如此

$var = "hello";
${$var} = "world";
echo $hello;

你也可以这样做:

${"this is a test"} = "works";
echo ${"this is a test"}; //Works

几个星期前,我在流线型对象上玩了一个关于这个的游戏,得到了一些有趣的结果

$Database->Select->{"user id"}->From->Users->Where->User_id($id)->And->{"something > 23"};

答案 1 :(得分:3)

您正在寻找Variable Variables

$$string = "new value";

会让你致电

echo $id; // new value

稍后在您的脚本中

答案 2 :(得分:1)

你可以这样做

$$string = "new value";

juste double $

答案 3 :(得分:1)

回复您的编辑的第二个答案:

$result = mysql_query($sql);
$num = mysql_num_rows($result);
$i = 0;
$id = array();
$name = array();
$value = array();

if ($num > 0) {
  while ($row = mysql_fetch_assoc($result)) {
    $id[$i] = $row['id'];
    $name[$i] = $row['name'];
    $value[$i] = $row['value'];
    $i++;
  }
}

这会使用计数器$i作为结果数组的键来循环结果。

修改

回复您的评论的其他答案:

while ($row = mysql_fetch_assoc($result)) {
  foreach($row as $column_name => $column_value) {
    $temp_array[$column_name][$i] = $column_value;
  }
  $i++;
}

foreach ($temp_array as $name => $answer) {
  $$name = $answer;
}

此代码创建一个临时多维数组来保存列名称并为该数组周围的值创建值以创建变量变量数组。作为一个方面,我不得不使用临时数组,因为$$column_name[$i]不起作用,我很乐意看到这个问题的替代答案。

最后的注意事项@Paisal,我发现你从来没有接受过答案,如果我以前看过这个,我就不会付出那么大的努力!

答案 4 :(得分:0)

您指的是variable variables吗?

这将完成这样的事情:

$string = "id";
$$string = "new value";

这会生成一个变量$id,其值为"new value"

答案 5 :(得分:0)

不要那样做。只需使用数组。

$arr[$string] = 'new value';

参考:How do I build a dynamic variable with PHP?

答案 6 :(得分:0)

试试这个:

$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
$i = 0;

if ($num_rows) {
  while ($row = mysql_fetch_assoc($result)) {
    foreach($row AS $key => $value) {
       ${$key}[$i] = $value;
    }

    $i++;
  }
}

答案 7 :(得分:0)

对于我们这些需要详细解释事物的人来说......

// Creates a variable named '$String_Variable' and fills it with the string value 'id'
$String_Variable = 'id';

// Converts the string contents of '$String_Variable', which is 'id',
// to the variable '$id', and fills it with the string 'TEST'
$$String_Variable = 'TEST'; 

// Outputs: TEST
echo $id;

// Now you have created a variable named '$id' from the string of '$String_Variable'
// Essentially: $id = 'Test';