2016-10-18 95 views
1

我試圖實現簡單的東西,並想知道是否有可能。谷歌搜索這次無濟於事。可能這不可能,但我不確定。我有以下代碼:通過串聯訪問php變量

<?php 
    //Enter your code here, enjoy! 

$query1="yay"; 
$query2="it"; 
$query3="works"; 

for($x=1;$x<=3;$x++){ 
    $query="\$query".$x; //I need to assign the above variables 
    echo $query; 
} 

?> 

我想要的輸出是 「yayitworks」,而是我得到 「$ QUERY1 $ QUERY2 $ QUERY3」。有什麼方法可以得到我的結果嗎?我知道switch語句會幫助我實現這一點,但我只是好奇。

在此先感謝... :-)

+0

在美元符號前移除反斜槓? – Robert

回答

1

你想要的是可變的變量:如果你想有

$queries = array("yay", "it", "works"); 

for($x=0;$x<count($queries);$x++){ 
    $query = "\{$queries[$x]}"; //I need to assign the above variables 
    echo $query; 
} 

http://php.net/manual/en/language.variables.variable.php

$query = ${"query".$x}

+0

omg !!第一個變量函數,現在是變量變量。謝謝你的信息。我不知道這存在... :-) – user3889963

+0

@ user3889963我在我的原始答案中犯了一個錯誤,不知道你是否嘗試過,但我只是編輯它來修復它,現在應該正常工作。 – Mogzol

+0

沒問題...我檢查了文檔。感謝您的鏈接... :-) – user3889963

0

使用數組在一個變量中使用全路徑=而不是=

for($x=0;$x<count($queries);$x++){ 
    $query .= "\{$queries[$x]}"; //I need to assign the above variables 
} 
echo $query;