Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/275.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何将INCLUDE放入包含foreach条件的变量中_Php_Variables_Foreach_Include - Fatal编程技术网

Php 如何将INCLUDE放入包含foreach条件的变量中

Php 如何将INCLUDE放入包含foreach条件的变量中,php,variables,foreach,include,Php,Variables,Foreach,Include,我在包含多个ID的表中有一列。我可以使用每个id来定义文件的路径,即column contents=“1000 20201”可以定义为变量路径,如 /1/1000/content-1000.html /20/20201/content-20201.html 我已经编写了以下代码,几乎可以正常工作 $fids = $mcat['mcat_fmemids']; $fidsarr = explode(' ', $fids); foreach ($fidsarr as $fid) { $fincl

我在包含多个ID的表中有一列。我可以使用每个id来定义文件的路径,即column contents=“1000 20201”可以定义为变量路径,如

/1/1000/content-1000.html
/20/20201/content-20201.html
我已经编写了以下代码,几乎可以正常工作

$fids = $mcat['mcat_fmemids'];

$fidsarr = explode(' ', $fids);
foreach ($fidsarr as $fid) {
$fincl .= include "../content/".substr($fid, 0, -3)."/".$fid."/content-".$fid.".html";
}

echo "html code that goes above my variable";
echo $fincl;
echo "html code that goes below my variable";
上述代码的结果

代码的顺序混乱了。$fincl变量在我的html代码的上半部分上方(之前)回音,对于代码中指定了$fincl变量的每个文件,都有一个“1”回音。见下面的例子

content-1000.html content
content-20201.html content
"html code that goes above my variable"
"11"
"html code that goes below my variable"

知道发生了什么以及如何修复吗?

包含指令不会返回包含文件的输出。相反,它从文件中的return语句返回值(如果存在)。否则,如果包含成功,
include
将返回
True

现在,您正在连接include语句中的两个返回值(即
True
True
)。PHP将其转换为
“11”

如果不希望在此位置包含文件,可以使用输出缓冲区获取include语句的输出:

ob_start();
foreach (...) {
   include $some_file;
}
$contents = ob_get_contents();  // get all the content within the buffer
ob_clean();  // clear the buffer
ob_end();   // stop output buffering

print $contents; // print the output

谢谢你的解释。这就成功了。我想我需要进一步了解php如何返回值。是的,include语句有点棘手。有时返回成功状态,有时返回包含的php文件返回值。问题是,如果从包含的文件返回False,会发生什么情况?从外面看,好像包含失败了。。。
ob_start();
foreach (...) {
   include $some_file;
}
$contents = ob_get_contents();  // get all the content within the buffer
ob_clean();  // clear the buffer
ob_end();   // stop output buffering

print $contents; // print the output