如何在短码内返回Foreach

时间:2017-11-10 作者:loliki

我有以下代码

 function stock_agenda() {

        $days = json_decode(file_get_contents(\'json_file\'));

        unset($days[0]);

        return  \'<table class="table">
   <thead>
     <tr>
      <th> Title </th>
      <th>Content</th>
      <th>Date</th>
     </tr>
    </thead>
    <tbody>
     \'. foreach($days as $day){.\'
      <tr>
       <td>\'.$day[0].\'</td>
       <td>\'.$day[1].\'</td>
       <td>\'.$day[2].\'</td>
      </tr>
     \'. }.\'
     </tbody>
</table>\' ;
    }
如何将其分配给短代码?如果我写信foreach 内部return 方法我得到一个错误。

2 个回复
最合适的回答,由SO网友:Shibi 整理而成

正如我在评论中所说的,您可以像这样使用缓冲

function stock_agenda() {
    $days = json_decode(file_get_contents(\'json_file\'));
    unset($days[0]);
    ob_start(); // start buffer
    ?>
    <table class="table">
        <thead>
            <tr>
                <th> Title </th>
                <th>Content</th>
                <th>Date</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($days as $day) { ?>
            <tr>
                <td><?php echo $day[0]; ?></td>
                <td><?php echo $day[1]; ?></td>
                <td><?php echo $day[2]; ?></td>
            </tr>
            <?php } ?>
        </tbody>
    </table>
    <?php
    $output = ob_get_clean(); // set the buffer data to variable and clean the buffer
    return $output;
}

SO网友:Drupalizeme

You can use:

function stock_agenda() {

    $days = json_decode(file_get_contents(\'json_file\'));

    unset($days[0]);


    $include_variable = \'\';
    foreach($days as $day){
        $include_variable  .= <<<EOD
            <tr>
            <td>$day[0]</td>
            <td>$day[1]</td>
            <td>$day[2]</td>
            </tr>
            EOD;
    }

    $str = <<<EOD
        <table class="table">
        <thead>
        <tr>
        <th> Title </th>
        <th>Content</th>
        <th>Date</th>
        </tr>
        </thead>
        <tbody>
        $include_variable 
        </tbody>
        </table>
    EOD;

    return $str;
}
结束