【问题标题】:Using return in foreach not echo with medoo在 foreach 中使用 return 不与 medoo 相呼应
【发布时间】:2016-05-04 16:20:00
【问题描述】:

这是我需要工作的代码示例...

如果我使用“echo '...';”一切正常,但如果我使用“return '...';”我只会得到一条记录。我不想使用 echo 的问题是我在页面顶部获得了所有结果。我需要使用 return 因为我在页面的其他地方调用了这个函数。

谢谢!

    public function showForum()
{

    $cats = $this->db->query("SELECT * FROM forum_cats ORDER BY cat_order ASC")->fetchAll();

    foreach ($cats as $cat) {
        return '<table class="table forum table-striped">
            <thead>
            <tr>
                <th class="cell-stat"
                    style="background-image: url(\'\'); background-size: 50px; background-repeat: no-repeat; background-position: center;"></th>
                <th>
                    <h3>' . $cat['cat_name'] . '</h3>
                </th>
                <th class="cell-stat text-center hidden-xs hidden-sm">Topics</th>
                <th class="cell-stat text-center hidden-xs hidden-sm">Posts</th>
                <th class="cell-stat-2x hidden-xs hidden-sm">Last Post</th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td class="text-center"><i class="fa fa-question fa-2x text-primary"></i></td>
                <td>
                    <h4><a href="#">Frequently Asked Questions</a><br>
                        <small>Some description</small>
                    </h4>
                </td>
                <td class="text-center hidden-xs hidden-sm"><a href="#">9 542</a></td>
                <td class="text-center hidden-xs hidden-sm"><a href="#">89 897</a></td>
                <td class="hidden-xs hidden-sm">by <a href="#">John Doe</a><br>
                    <small><i class="fa fa-clock-o"></i> 3 months ago</small>
                </td>
            </tr>
            </tbody>
        </table>';

    }
}

【问题讨论】:

  • 是的,因为return 结束了函数的执行。相反,在您的循环中,将字符串设置为一个数组项,然后在循环之后返回该数组。然后,您可以稍后回显。
  • 我编辑了我的评论,建议将每个字符串存储在一个数组中,另一种选择是连续连接字符串并返回最终字符串。
  • 感谢@JonStirling 的建议! :)

标签: php foreach medoo


【解决方案1】:

将所有要返回的数据存储在一个字符串中,稍后再返回该字符串:

public function something() {
    $result = ""; // Create empty string

    foreach($array as $val) {
        $result .= "something"; // Add something to the string in the loop
    }

    return $result; // Return the full string
}

另一种选择(因为您已经有一个数组)是将数组映射到您的字符串值并像这样重新处理内爆数组:

public function something() {
    return implode('', array_map(function($val) {
        return "something";
    }, $array));
}

【讨论】:

  • 这个怎么样:paste.md-5.net/roxirenudu.coffee,我现在进错论坛了...
  • 您需要在第二个 foreach 中设置$display_forums = ""; inside,但实际上您根本不需要两个变量!您可以继续连接到您的第一个。
猜你喜欢
  • 1970-01-01
  • 2013-11-20
  • 2017-02-02
  • 2012-07-04
  • 1970-01-01
  • 2018-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多