开发者

Random link without repeat - User session

I have 7 links and I need to display one link per page or page view wi开发者_运维知识库thout repeat the links from previous views.

The links need to be displayed in a random way and all 7 links must be shown to the user if he/she visit 7 pages, (one per page), if the user visit more than 7 pages the cicle will start again.

I hope the question is clear. Thanks and sorry for my english Daniel


You should store the previously visited links in the session or database. you can simply shuffle the links, and iterate trough. Then check if it's been visited before - and keep on going until you find one. If you can't find on (done iteration) you can assume all 7 has been visited, and you can reset the session/database.

Small code example (note: pseudocode).

$aLinks = array(1, 2, .., ..);
shuffle($aLinks);

$sLinkToShow = null;
foreach($aLinks as $aLink) {
    if (seenBefore()) continue;
    $sLinkToShow = $aLink['link'];
}

if (is_null($sLinktoShow)) { 
    // seen all
}
echo $sLinkToShow;


Store the shuffled links in the session and use them one by one:

$links = array('a', 'b', 'c', …);

if (empty($_SESSION['links'])) {
    // first time visit, populate random order in session
    $_SESSION['links'] = array_keys($links);
    shuffle($_SESSION['links']);
}

// pop first link
$link = array_shift($_SESSION['links']);

// cycle array; or don't, to create a different order next time
$_SESSION['links'][] = $link;

// output link
echo $links[$link];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜