Php 在foreach中使用return而不是与medoo一起使用echo

Php 在foreach中使用return而不是与medoo一起使用echo,php,foreach,medoo,Php,Foreach,Medoo,这是我的代码,我需要得到工作的例子 如果我使用“echo”…;“一切正常,但如果我使用“return”…;“我只得到一条记录。我不想使用echo的问题是,我会在页面顶部获得所有结果。我需要使用return,因为我在页面的其他地方调用了这个函数 谢谢 public function showForum() { $cats = $this->db->query("SELECT * FROM forum_cats ORDER BY cat_order ASC")->

这是我的代码,我需要得到工作的例子

如果我使用“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>';

    }
}
公共功能showForum()
{
$cats=$this->db->query(“按cats\u ORDER ASC从论坛中选择*)->fetchAll();
foreach($cats作为$cat){
返回'
“.$cat['cat_name']”
话题
帖子
最后一篇文章

一些描述 通过
三个月前 '; } }
将要返回的所有数据存储在字符串中,然后返回字符串:

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));
}

是,因为
return
结束函数的执行。相反,在循环中,将字符串设置为数组项,并在循环后返回数组。然后您可以稍后回显。我编辑了我的评论,建议将每个字符串存储在一个数组中,另一个选项是连续对字符串进行concat,然后只返回最后一个字符串。谢谢@JonStirling!的建议:)这是怎么回事:,我现在得到了错误的论坛…你需要设置
$display\u forums=“”在第二个foreach中,但实际上您根本不需要两个变量!你可以继续连接到你的第一个。