PHP字符串作为变量名

4

$string = "id";
希望结果如下 $id = "新值";

我该如何在php中编写这个代码?

编辑..

以下怎么样?


$column = array("id","name","value");
假设从mysql中找到3行
想要的结果是 $id[0] = "3"; $id[1] = "6"; $id[2] = "10"; $name[0] = "a"; $name[1] = "b"; $name[2] = "c"; $value[0] = "蝙蝠"; $value[1] = "老鼠"; $value[2] = "猫";

虽然PHP允许您这样做(如下面的答案所示),但通常认为这是一个不好的设计原则,它会使您的代码难以维护。更好的方法可能是使用关联数组,例如$my_array ['id'] ="new value"; - Gareth
1
你需要为更新创建一个单独的问题。 - RobertPitt
8个回答

9

有两种主要方法

第一种是使用双重 $ (变量变量),如下所示

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

3

您正在寻找变量变量

$$string = "new value";

将允许您调用

echo $id; // new value

在您的脚本中稍后,

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,我看到你从未接受过答案,如果我之前看到了这个,我就不会付出这么多的努力了!

如果不想手动定义变量id、name和value,而是想从$column数组中获取它们,该怎么办呢?我希望你能理解我为什么要定义$column数组。 - Paisal
@Paisal,我已经更新了我的答案,以动态创建列名变量。请记住@Marco Mariani所说的代码难以阅读。 - Alan Whitelaw

1

你可以做到这件事

$$string = "new value";

只需双倍 $


0

不要使用变量变量?如果您不介意的话,您的理由是什么? - Alan Whitelaw

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

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

0
你是在指 变量 吗?
这将会实现类似于这样的效果:
$string = "id";
$$string = "new value";

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接