带有连接字符串的PHP变量变量名

时间:2017-02-04 08:39:51

标签: php mysql

假设我有一个mysql查询:

$qry = "SELECT name,date,id,size from table";
$stmt = $db->query($qry);
while($r = $stmt->fetch()){
      foreach ($r as $k => $v){
          $$k = $v;
      }
}

这很有道理,也很好用。它给了我变量,如:

    $name = 'someVal';
    $date = 'someOtherVal';

现在假设我想做另一个可能有重叠字段的查询。我希望在给定相同格式的变量名称前加上“t_”。

$qry = "SELECT name,occupation,date from otherTable";
$stmt = $db->query($qry);
while($r = $stmt->fetch()){
      foreach ($r as $k => $v){
          $$k = $v;
      }
}

我怎么能拥有它所以这个查询的结果给了我带有前置“t _”的可变名称;

 $t_name = 'someVal';
 $t_occupation = 'someOtherVal';

2 个答案:

答案 0 :(得分:2)

 $qry = "SELECT name,occupation,date from otherTable";
 $stmt = $db->query($qry);
 while($r = $stmt->fetch()){
    foreach ($r as $k => $v){
        $varname = "t_".$k;
        $$varname = $v;
    }
 }

答案 1 :(得分:0)

只需更改

$$k = $v;

代表

$$("t_".$k) = $v;

它会起作用。