Randomizing foreach expression and including URL r

2019-09-08 06:18发布

问题:

This might be a little complicated..!

Here's what I got so far:

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

    $i++; 

    //echo $link;
}

$i = Counts all posts on my website.

$link = provide a link to the post.

After fetching how many posts I have with $i, I need to randomize a value between 1-"Total Posts" and instead of echoing out the random value it should redirect the website to the respective $link. Can someone please enlighten me?

回答1:

You can use the function array_rand to obtain a random key in $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]);

If you have a fetish for one-liners header("Location: ".$posts[array_rand ($posts)][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]);


标签: php random