繁体   English   中英

php字符串名称作为变量

[英]php string name as variable


$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";

Theres 2主要方法

第一个是双$变量变量 ),就像这样

$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"};

您正在寻找变量变量

$$string = "new value";

会让你打电话

echo $id; // new value

稍后在你的脚本中

你可以这样做

$$string = "new value";

juste double $

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

$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,我发现你从来没有接受过答案,如果我以前看过这个,我就不会付出太多努力!

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

// 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';

你指的是变量变量吗?

这将完成这样的事情:

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

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

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

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

参考: 如何使用PHP构建动态变量?

尝试这个 :

$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++;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM