php里面我获取到最新文章,最新评论,最新注册会员数据混合一起,并且以时间为排序,循环输出

您可以将最新文章、最新评论、最新注册会员的数据存放在不同的数组中。然后将三个数组合并成一个数组,使用 usort() 函数以时间为排序,循环输出即可。以下是示例代码:

// 获取最新文章、最新评论、最新注册会员数据
$latestPosts = getLatestPosts();   // 假设获取最新文章的函数为 getLatestPosts()
$latestComments = getLatestComments();   // 假设获取最新评论的函数为 getLatestComments()
$latestMembers = getLatestMembers();   // 假设获取最新注册会员的函数为 getLatestMembers()

// 将三个数组合并成一个数组
$allLatest = array_merge($latestPosts, $latestComments, $latestMembers);

// 使用 usort() 函数以时间为排序
usort($allLatest, function($a, $b) {
    return strtotime($b['time']) - strtotime($a['time']);
});

// 循环输出
foreach ($allLatest as $item) {
    echo $item['title'] . ' - ' . $item['time'] . '<br>';
}

假设三个函数都返回含有 'title''time' 字段的数组,且时间字段格式为 'Y-m-d H:i:s',数组格式如下:

// 最新文章数据格式
$latestPosts = [
    [
        'title' => '文章标题1',
        'time' => '2021-01-01 10:00:00'
    ],
    [
        'title' => '文章标题2',
        'time' => '2021-01-02 12:00:00'
    ],
];

// 最新评论数据格式
$latestComments = [
    [
        'title' => '评论标题1',
        'time' => '2021-01-02 08:00:00'
    ],
    [
        'title' => '评论标题2',
        'time' => '2021-01-03 09:00:00'
    ],
];

// 最新注册会员数据格式
$latestMembers = [
    [
        'title' => '会员名称1',
        'time' => '2021-01-03 10:30:00'
    ],
    [
        'title' => '会员名称2',
        'time' => '2021-01-04 11:00:00'
    ],
];

输出结果应该如下:

会员名称2 - 2021-01-04 11:00:00
评论标题2 - 2021-01-03 09:00:00
会员名称1 - 2021-01-03 10:30:00
文章标题2 - 2021-01-02 12:00:00
评论标题1 - 2021-01-02 08:00:00
文章标题1 - 2021-01-01 10:00:00

请注意,以上示例代码仅为演示用途,实际实现需要根据您的数据结构稍作修改。

文章由官网发布,如若转载,请注明出处:https://www.veimoz.com/2046
0 评论
357

发表评论

!