在foreach中使用return而不是使用medoo

时间:2016-05-04 16:20:00

标签: php foreach medoo

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

如果我使用"回声' ...&#39 ;; "一切都好,但如果我使用"返回' ...&#39 ;; "我只得到一条记录。我不想使用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>';

    }
}

1 个答案:

答案 0 :(得分:0)

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

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