我正在尝试将网站首页的一系列元素的顺序随机化。
假设我们在此页面上显示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
。有任何想法吗,
奇妙
编辑。
如果我们有多个要素,我们将需要做什么。
$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
需要保持在一起并一起洗牌。有任何想法吗
最佳答案
将文本放入array
并shuffle
。
<?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');
关于php - PHP元素的随机重排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5459011/