随机化foreach表达式并包括URL重定向

时间:2011-12-10 09:43:21

标签: php

这可能有点复杂..!

这是我到目前为止所得到的:

$i = 0;
foreach ($posts as $post) {
    $link = $post[1];
    $title = $post[2];

    $i++; 

    //echo $link;
}

$i =计算我网站上的所有帖子。

$link =提供帖子的链接。

在获取$i的帖子数量之后,我需要在1-“总帖子数”之间随机化一个值,而不是回显随机值,它应该将网站重定向到相应的{{1} }。有人可以赐教我吗?

2 个答案:

答案 0 :(得分:4)

您可以使用array_rand功能获取$posts

中的随机密钥
$posts = array (
  array ('0', 'http://stackoverflow.com', 'SO'),
  array ('1', 'http://google.com',    'Google'),
  array ('2', 'http://youtube.com',  'Youtube'),
  array ('3', 'http://4chan.org',      '4chan')
);

// ...

$random_entry_key = array_rand ($posts);
$random_entry     = $posts[$random_entry_key];

header ("Location: " . $random_entry[1]);

如果您对单行header("Location: ".$posts[array_rand ($posts)][1]);

感到迷恋

答案 1 :(得分:2)

$i = rand(0, count($posts) - 1); // if $posts has 10 items, rand will return
                                 // an integer between 0 and 9 (both inclusive)
header('Location: ' . $posts[$i][1]);