如何在每个组中循环具有不同内容的代码组?

时间:2013-08-02 18:35:05

标签: php

我正在写一个MyBB插件。它现在正在工作,但在尝试循环代码集时遇到了一些问题。

例如。我正在使用此代码从数据库中获取数据。

//Some codes...
$lctg_rcposts .= '
    <div class="bt-lite">
    <div class="bt-link">Newest Posts</div>
    <div id="bt-holder">';

$count = $db->simple_select("threads", "COUNT(tid) AS threads", "$uview");
$threadcount = $db->fetch_field($count, "threads");
$sets = $threadcount / $totalsets;

for ($i=1; $i<=$sets; $i++)
{
    $lctg_rcposts .= '<div class="bt-set">';
    $query = $db->query("SELECT t.*
        FROM ".TABLE_PREFIX."threads AS t
        $ufids AND t.visible = '1' GROUP BY t.tid
        ORDER BY t.lastpost DESC LIMIT 3"
    );

    while($data = $db->fetch_array($query))
    {
        $datacache['tid'] = $data;
    }

    if(!empty($datacache))
    {
        foreach($datacache as $data)
        {
            //Some code...
            $lctg_rcposts .= '
            <a href="thread-' . $data['tid'] . '-lastpost.html">
            ' . $subject .'
            </a>';
        }
    }

    $lctg_rcposts .= '</div>'; //--- End of Sets
}

$lctg_rcposts .= '</div></div>'; //--- End of File

问题是每组的内容都是相同的(当然)。但我希望这将有如下模型。 (好的一套只有3个链接)

<div class="bt-set>
<a>1</a>
<a>2</a>
<a>3</a>
</div>
<div class="bt-set>
<a>4</a>
<a>5</a>
<a>6</a>
</div>
... and goes on ...

请给我一些建议。非常感谢。

1 个答案:

答案 0 :(得分:2)

如果您想要的大小,可以使用array_chunk将$ datacache数组分解为数组。

if(!empty($datacache))
{
    foreach(array_chunk($datacache, 3, true) as $chunk)
    {
        //put <div> here
        foreach ($chunk as $data) {
            //Some code...
            $lctg_rcposts .= '
            <a href="thread-' . $data['tid'] . '-lastpost.html">
            ' . $subject .'
            </a>';
        }
        //put </div> here
    }
}

希望这有帮助。