duanluan3651
2014-08-27 03:55
浏览 75
已采纳

PHP在字符串中的字符串中变量

I am attempting to echo a sting containing a variable already stored in a variable. Essentially I am building a class that can dynamically build tables based on a changing number of columns. I need get my db field names into the foreach loop before the foreach loop that has my db results, and then iterate over them in the loop. The problem is I have to store them in a loop prior to the db results loop; which is not recognizing it as a variable and just giving me a plain text '$row['myVar']'.

How can I get this to recognize the variable in the second loop?

$sqlVarNames = explode(', ', $sqlVar);
foreach ($sqlVarNames as $columnVar) {
    $finalColumnVars .= '<td>\'. $row[\''.$columnVar.'\'] .\'</td>';
}

and then into my second loop

foreach ($sqlResult as $row) {
    echo '<tr>';
    echo $finalColumnVars;
    echo '</tr>';
} 

I tried all sorts of escape sequences on my $finalColumnVars and can't seem to get it to output the variable instead on plain text.

Here is what I get with the above code

<td>'. $row['client_name'] .'</td>

Is this possible?

图片转代码服务由CSDN问答提供 功能建议

我试图回显一个包含已存储在变量中的变量的sting。 基本上我正在构建一个可以根据不断变化的列数动态构建表的类。 我需要在具有我的db结果的foreach循环之前将我的db字段名称放入foreach循环中,然后在循环中迭代它们。 问题是我必须在db结果循环之前将它们存储在循环中; 它没有将它识别为变量而只是给我一个纯文本'$ row ['myVar']'。

如何识别第二个循环中的变量?

  $ sqlVarNames = explode(',',$ sqlVar); 
foreach($ sqlVarNames as $ columnVar){
 $ finalColumnVars。='&lt; td&gt; \'  。  $ row [\''。$ columnVar。'\']。\'&lt; / td&gt;'; 
} 
   
 
 

然后进入我的第二个循环

  foreach($ sqlResult as $ row){
 echo'&lt; tr&gt;'; 
 echo $ finalColumnVars; 
 echo'&lt; / tr&gt;';  
} 
   
 
 

我在$ finalColumnVars上尝试了各种转义序列,似乎无法在纯文本上输出变量。

以下是上述代码

 &lt; td&gt;'。  $ row ['client_name']。'&lt; / td&gt; 
   
 
 

这可能吗?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doupeng2253 2014-08-27 04:05
    已采纳

    here is how you can merge these two loop and get the desired.

    $sqlVarNames = explode(', ', $sqlVar);
    foreach ($sqlResult as $row) {
        echo '<tr>';
        foreach ($sqlVarNames as $columnVar) {
            echo '<td>'. $row[$columnVar] .'</td>';
        }
        echo '</tr>';
    } 
    
    打赏 评论
  • duankangpazhuo0347 2014-08-27 03:58
    $sqlVarNames = explode(', ', $sqlVar);
    foreach ($sqlVarNames as $columnVar) {
        $finalColumnVars .= '<td>'.$row[$columnVar].'</td>';
    }
    
    打赏 评论

相关推荐 更多相似问题