PHP循环动态变量 [英] PHP Loop Dynamic Variable

查看:238
本文介绍了PHP循环动态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个动态变量.我有一个循环,我希望它循环遍历记录并为每个记录创建一个变量.我的代码:

I am trying to create a dynamic variable. I have a loop and I want it to loop through the records and create a variable for each record. My code:

$ct = 1;
foreach ($record as $rec){
  $var.$ct = $rec['Name'];
  $ct = $ct + 1;
}

echo $var1;

当我尝试使用上面的代码时,它给我一个错误,提示$var1变量不存在/未定义?在PHP中是否可以像上面的示例一样创建动态变量.如果是这样,我在做什么错?

When I try to use the above code, it gives me an error saying the $var1 variable doesn't exist/undefined? Is it possible in PHP to create dynamic variables like the above example. If so, what am I doing wrong?

推荐答案

您正在寻找变量.

将变量名创建为字符串,然后分配它:

Create the variable name as a string, and then assign it:

$ct = 1;
foreach( $record as $rec )
{
  $name = 'var'.$ct;
  $$name = $rec['Name'];
  $ct++;
}

echo $var1;

创建数组会更好,

$names = [ ];

foreach( $record as $rec )
{
  $names[] = $rec['Name'];
}

echo $names[0];

这篇关于PHP循环动态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆