开发者

PHP random reorder of elements

开发者 https://www.devze.com 2023-02-20 01:43 出处:网络
I am trying to randomise the order of a series of elements for a websites homepage. Imagine w开发者_JAVA技巧e have 3 titles to display on this page.

I am trying to randomise the order of a series of elements for a websites homepage.

Imagine w开发者_JAVA技巧e have 3 titles to display on this page.

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

Now on the HTML file we want to display these but in a random order and never repeating one element.

<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>

Also it must avoid ever repeating $title1 $title2 or $title 3 on the page.

Any ideas,

Marvellous

EDIT.

What would we need to do if we had more than one element.

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

Same principle but obviously $info1 and $title1 need to stay together and be shuffled together.

Any ideas


Put them into an array and shuffle it using shuffle:

$titles = array($title1, $title2, $title3);
shuffle($titles);
foreach ($titles as $i => $title) {
    echo '<div id="titleholder'.($i+1).'">'.htmlspecialchars($title).'</div>';
}


Put the text into an array and shuffle it.

<?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


Update

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


You can copy the strings to an array and then call shuffle function which randomly shuffles the array.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号