(PHP)前n个帖子中有特定帖子的随机帖子顺序?

(PHP)前n个帖子中有特定帖子的随机帖子顺序?,php,random,shuffle,Php,Random,Shuffle,我正在处理一个页面,使用PHP的shuffle()函数以随机顺序显示帖子。有一个特定的标题帖子应该总是在前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 或 有人能给我一个如何实现这一点的提示吗?谢谢 我假设您从数据库中获取列表,并且在另一个变量中有“title post” 您可以简单地执行以下操作: $array = array('post-1',

我正在处理一个页面,使用PHP的shuffle()函数以随机顺序显示帖子。有一个特定的标题帖子应该总是在前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


有人能给我一个如何实现这一点的提示吗?谢谢

我假设您从数据库中获取列表,并且在另一个变量中有“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
这应该能奏效


编辑:评论

这应该适合您:

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


你是从数据库里得到的吗?。然后你可以尝试order by rand()limit 5是的,我会这样做:从数组中删除有问题的帖子,随机化数组,然后在前五个位置随机拼接帖子。
$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
<?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