【问题标题】:(PHP) random post order with specific post within first n posts?(PHP)在前n个帖子中具有特定帖子的随机帖子顺序?
【发布时间】:2014-12-18 10:03:32
【问题描述】:

我正在处理一个页面,使用 PHP 的 shuffle() 函数以随机顺序显示帖子。有一个特定的 title-post 应该总是在前 5 个帖子中弹出。可能是这样的:

1. Post-7
2. Post-2
3. Post-1
4. Title-Post
5. Post-5
6. Post-4
7. Post-3
8. Post-6

1. Post-2
2. Title-Post
3. Post-4
4. Post-6
5. Post-1
6. Post-3
7. Post-7
8. Post-5

有人可以告诉我如何实现这一目标吗?谢谢!

【问题讨论】:

  • 您是从数据库中获取此信息的吗?比你可以尝试按 rand() 限制 5 订购

标签: php random shuffle


【解决方案1】:

我假设您从数据库中获取列表,并且您在另一个变量中有“title-post”。

您可以简单地执行以下操作:

$array = array('post-1', 'post-2', 'post-3'); //the array you should get from the DB
shuffle($array); //shuffle all
$title = 'Title-Post';

array_splice( $array, rand(0, 4), 0, $title); //insert the title somewhere between 0 and 4 so in the first 5 values

这应该可以解决问题

编辑:cmets

【讨论】:

  • 是的,我会这样做:从数组中删除有问题的帖子,随机化数组,然后在前五个位置随机拼接帖子。
【解决方案2】:

这应该适合你:

(我只是生成一个介于 0 和 4 之间的随机数,如果不是标题帖子,我将帖子放在末尾并将标题帖子放在那个位置)

<?php

    $input = array("Post-7", "Post-2", "Post-1", "Title-Post", "Post-5", "Post-4", "Post-3", "Post-6");
    $titel = rand(0, 4);
    shuffle($input);

    if($input[$titel] != "Title-Post") {
        $input[] = $input[$titel];
        $temp = $input[array_search("Title-Post", $input)];
        unset($input[array_search("Title-Post", $input)]);
        $input[$titel] = $temp;
    }

    foreach($input as $value)
        echo $value . "<br />";

?>

可能的输出:

Post-2
Post-1
Title-Post
Post-6
Post-7
Post-5
Post-3
Post-4

【讨论】:

    猜你喜欢
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-29
    • 2016-07-21
    • 1970-01-01
    • 2019-04-06
    相关资源
    最近更新 更多