PHP随机重新排序元素

时间:2011-03-28 12:32:03

标签: php random

我正在尝试将网站主页的一系列元素的顺序随机化。

想象一下,我们在此页面上显示了3个标题。

$title1 = 'the first title';
$title2 = 'the second title';
$title3 = 'the third title';

现在,在HTML文件中,我们希望以随机顺序显示这些内容,而不是重复一个元素。

<html>
<div id='titleholder1'> [ randomly show either $title1, $title2 or $title3 ] </div>
<div id='titleholder2'> [ randomly show either $title1, $title2 or $title3 ] </div>
<div id='titleholder3'> [ randomly show either $title1, $title2 or $title3 ] </div>

</html>

此外,它必须避免在页面上重复$title1 $title2 or $title 3

任何想法,

非凡

EDIT。

如果我们有多个元素,我们需要做什么?

$title1 = 'the first title';    $info1 = 'the first info';
    $title2 = 'the second title';     $info2 = 'the second info';
    $title3 = 'the third title';    $info3 = 'the third info';

同样的原则,但很明显$info1$title1需要保持在一起并被拖曳在一起。

任何想法

3 个答案:

答案 0 :(得分:3)

将它们放入数组并使用shuffle

对其进行随机播放
$titles = array($title1, $title2, $title3);
shuffle($titles);
foreach ($titles as $i => $title) {
    echo '<div id="titleholder'.($i+1).'">'.htmlspecialchars($title).'</div>';
}

答案 1 :(得分:3)

将文字放入arrayshuffle

<?php
$titles[] = 'one';
$titles[] = 'two';
$titles[] = 'three';

shuffle($titles);
?>

<div class="titleholder1"><?php echo $titles[0];?></div>
<div class="titleholder2"><?php echo $titles[1];?></div>
<div class="titleholder3"><?php echo $titles[2];?></div>

php.net/shuffle


更新

$webpage[] = array('info' => 'first info', 'title' => 'first title');
$webpage[] = array('info' => 'second info', 'title' => 'second title');
$webpage[] = array('info' => 'thrid info', 'title' => 'third title');

答案 2 :(得分:1)

您可以将字符串复制到数组中,然后调用shuffle函数,随机抽取数组。