变量中的Php变量

时间:2010-12-31 18:14:09

标签: php

我有一段看起来像这样的代码:

$result = mysql_query($queryc) or die(mysql_error());   

if(mysql_num_rows($result) > 0)                             
{   
  while($row = mysql_fetch_array($result, MYSQL_ASSOC))
  {
    echo $row['$field']; 
  }
}

假设代码在函数中,我想将$ field传递给$ row ['']我将如何实现?

换句话说,我试图使用$ row ['$ field'];和$ field在别处定义

4 个答案:

答案 0 :(得分:4)

你不会在$field周围加上任何引号......就像这样:

echo $row[$field];

答案 1 :(得分:4)

假设您有此功能定义:

function foo($field) {
    // from that code you have given
    ....
    echo $row[$field];  // no need of the quotation marks around $field
    ....
}

答案 2 :(得分:3)

单引号禁止变量替换。

echo $row["$field"];

或只是

echo $row[$field];

强烈建议使用后者,因为它不需要PHP将$row["$field"]解析为$row[$field]。在每次迭代中为您节省一些microtime。

答案 3 :(得分:3)

变量不会用单引号扩展;它们只是expanded in double quotes or in the heredoc syntax

  

当用双引号或heredoc指定字符串时,会在其中解析变量。

所以要么使用双引号,要么更好,只是省略它们:

$row[$field]