簡體   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