doukuangxiu1621 2014-04-24 11:14
浏览 69
已采纳

PHP在设置值后在foreach中使用变量名称

EDIT: SOLVED


ORIGINAL POST:

I have a foreach loop which creates variables in the form of:

    foreach ($fieldsarray as $field)
    {
        ${$field} = $globalrow[$field];
    }

This creates variables using array elements, like $firstname, $lastname, etc.

Now, since the values of these variables are fetched from the DB, I cannot use the variable names again in the same foreach. What I would like to do is to use this in the loop:

if(!empty($$field)) 
  {
    $r.$field='<tr><td width="50%">'.${$field}._label.': </td>
    <td width="50%">'.${$field}.'</td></tr>';
  }

Basically, this would generate table rows with data from DB, but only if the value of the variable is not empty.

My problem is: Since I have declared above that e.g. $firstname = 'John' - then the second part of the code does not work anymore, because I assume PHP does not transform the above snippet into

if(!empty($firstname))

but rather into

if(!empty(John))

How can I "force" PHP to again use the variable NAME rather than its value in this case?

Thank you for your help.

EDIT: OK, cheezeburgers suggestions worked and I think now it's working as intended. Thanks to all of you for your help.

EDIT 2: The table rows are output correctly on the screen, e.g.:

First Name: John
Last Name : Smith

but for some weird reason in the email confirmation the output is doubled:

First Name: John
Last Name : Smith
First Name: John
Last Name : Smith

In both cases I simply echo them with:

<?php echo $allrows ?>

where $allrows is in the foreach loop.

(I will post this part as a new question since this seems to be a new problem now)

  • 写回答

2条回答 默认 最新

  • douyan4958 2014-04-24 11:21
    关注

    PHP will work it out fine, just that you have missed the quote around _label and probably that's being read as a constant.

    Try this:

    $$field='<tr><td width="50%">'.${$field}.'_label: </td>
    <td width="50%">'.${$field}.'</td></tr>'; 
    

    which gives the output as:

    John_label: John
    

    Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。