php foreach里面的变量

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php foreach里面的变量相关的知识,希望对你有一定的参考价值。

我试图循环txt2的记录,但如果我把foreach放在txt2之外,我只得到一组记录,这就是问题所在。获取记录输出的简单方法是什么?

<?php
$batfile = fopen("CNC/$wrtID/$wrtID.bat", "w") or die("Unable to open file!");


$txt1 = "
@ECHO OFF
@ECHO **** Run NC-Generator WOODWOP 4.0 ****";
?>
<?php
$txt2 = "
foreach($queryRecords as $res)
 {
 $code = $res['code'];
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-$code-el.mpr
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-$code-er.mpr
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-$code-tb.mpr
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-$code-dc.mpr
 }
";
 ?>
<?php
$txt3 ="
@ECHO **** Done ****
";
fwrite($batfile, $txt1);
fwrite($batfile, $txt2);
fwrite($batfile, $txt3);
fclose($batfile);
?>
答案

不要把foreach放在字符串里面,只是用.=连接:

$txt2 = "";
foreach($queryRecords as $res)
{
$code = $res['code'];
$txt2 .= "
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-$code-el.mpr
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-$code-er.mpr
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-$code-tb.mpr
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-$code-dc.mpr";
}

如果你不需要将它们分开,只需将它们连接成一个$txt

$txt = "
@ECHO OFF
@ECHO **** Run NC-Generator WOODWOP 4.0 ****";

foreach($queryRecords as $res)
{
$code = $res['code'];
$txt .= "
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-$code-el.mpr
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-$code-er.mpr
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-$code-tb.mpr
NCWEEKE.exe -n=C:/WW4/$wrtID/$wrtID-$code-dc.mpr";
}
$txt .= "
@ECHO **** Done ****
";
fwrite($batfile, $txt);

以上是关于php foreach里面的变量的主要内容,如果未能解决你的问题,请参考以下文章

PHP中使用foreach循环读取数组数据的方法

PHP Foreach 和未设置变量

php学习笔记-foreach循环

结合数组和变量php [重复]

一次php foreach 变量作用域的踩坑记录

在PHP Laravel中将变量从foreach循环传递给我的控制器