PHP字符串名称作为变量
$string = "id";
want result to be like
$id = "new value";
如何在PHP中对此进行编码?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";
响应您的编辑第二个答案:
$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;
}
此代码创建一个临时多维数组来保存列名和值围绕阵列的循环来创建您的变量变量数组。作为一方,我不得不使用temp数组作为$$column_name[$i]
不起作用,我很想看到这个问题的替代答案。
最后说明@佩萨尔,我看到你从未接受过答案,如果以前我看到过,我不会付出这么多努力!
你可以做到这一点
$$string = "new value";
juste double $
您指的是variable variables?
这将完成这样的事情:
$string = "id";
$$string = "new value";
这将产生一个变量$id
与价值"new value"
。
即使世界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 ...//
,第二种方法是使用{}
LIK所以
$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"};
谢谢我有新的问题(编辑上面) – Paisal 2011-01-11 10:59:38
不要做变量变量?如果你不介意我问,你有什么推理呢? – 2011-01-11 10:50:13
试试这个:
$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++;
}
}
对于我们这些谁需要的东西在非常详细的解释...
// 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';
虽然PHP也允许你这样做(如下显示的答案)它通常被认为是一个糟糕的设计原则,它会让你的代码难以维护。更好的方法可能是使用关联数组,例如`$ my_array ['id'] =“new value”;` – Gareth 2011-01-11 10:47:16
您将不得不为更新创建一个单独的问题。 – RobertPitt 2011-01-11 11:41:16