【问题标题】:How to put an INCLUDE into a variable that contains a foreach condition如何将 INCLUDE 放入包含 foreach 条件的变量中
【发布时间】:2017-01-23 22:46:44
【问题描述】:

我的表中有一个包含多个 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"

任何想法正在发生什么以及如何解决它?

【问题讨论】:

    标签: php variables foreach include


    【解决方案1】:

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

    您现在连接包含语句的两个返回值(即TrueTrue)。 PHP 将此转换为"11"

    $fids = $mcat['mcat_fmemids'];
    $fidsarr = explode(' ', $fids);
    
    echo "html code that goes above my variable";
    foreach ($fidsarr as $fid) {
       include "../content/".substr($fid, 0, -3)."/".$fid."/content-".$fid.".html";
    }
    echo "html code that goes below my variable";
    

    如果你不想在这个地方包含文件,你可以使用输出缓冲区来获取包含语句的输出:

    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 会发生什么?从外面看起来好像包含失败了......
    猜你喜欢
    • 2011-10-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多