You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP数组按日期分组渲染HTML布局问题求助

Hey there, I totally feel your pain—pulling an all-nighter chasing a layout bug is brutal. Let's fix this grouping issue for you right away.

The core problem with your current code is that it only adds the date heading when the date changes, but it doesn't wrap each date's posts in a container (<div class="one">). We need to handle opening and closing these containers properly as we loop through the posts.

Here's the revised code that will give you the exact structure you want:

$html = '';
$last_date = '';
$in_container = false; // Track if we're inside a date container

foreach ($nposts as $post) {
    if ($post['post_date'] != $last_date) {
        // Close the previous container if we were in one
        if ($in_container) {
            $html .= '</div>';
        }
        
        // Start a new date container
        $html .= '<div class="one">';
        $html .= '<h3>' . $post['post_date'] . '</h3>';
        
        $last_date = $post['post_date'];
        $in_container = true;
    }
    
    // Add the post inside the current container
    $html .= '<div class="two">id: ' . $post['ID'] . ' ' . $post['title'] . '</div>';
}

// Don't forget to close the last container
if ($in_container) {
    $html .= '</div>';
}

echo $html;

What changed:

  • Added $in_container to track when we're inside a date group container
  • When the date changes, we first close the previous container (if it exists) before opening a new one
  • Removed the <br> tags since we're using proper container divs now
  • Added a final check to close the last container after the loop ends (this is easy to forget!)

This will output HTML exactly like your desired example: each date gets its own <div class="one"> wrapper, with the heading and all related posts inside as <div class="two"> elements.

Take a break after this—you've earned it!

内容的提问来源于stack exchange,提问作者RQEST

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:41:31