user2398026
user2398026

Reputation: 51

ForEach Random Array

I'm trying to make a script that redirects to a random YouTube video. How would I take the vidKey, put each $vidkey in an array and then randomize that array so you get redirected to a different YouTube video?

$sxml = simplexml_load_file("http://gdata.youtube.com/feeds/api/users/TechTubeCentral/uploads?max-results=25");
foreach ($sxml->entry as $entry) {
  $vidKey = substr(strrchr($entry->id,'/'),1);
}

Upvotes: 1

Views: 378

Answers (3)

Mark Parnell
Mark Parnell

Reputation: 9200

PHP has a built-in function for selecting a random element (or elements) from an array, array_rand()

$sxml = simplexml_load_file("http://gdata.youtube.com/feeds/api/users/TechTubeCentral/uploads?max-results=25");
$vidKeys = array();
foreach ($sxml->entry as $entry)
    $vidKeys[] = substr(strrchr($entry->id,'/'),1);
$randomVidKey = $vidKeys[array_rand($vidKeys)];

Upvotes: 0

nice ass
nice ass

Reputation: 16729

Put each key into an array, then shuffle it when you're done:

$sxml = simplexml_load_file("http://gdata.youtube.com/feeds/api/users/TechTubeCentral/uploads?max-results=25");
$vidKeys = array();
foreach ($sxml->entry as $entry)
  $vidKeys[] = substr(strrchr($entry->id,'/'),1);

shuffle($vidKeys);

Then just pick one entry from it, like $vidKeys[0].

You could also put the results in the database and ORDER BY RAND(). On next request you get the video keys from the DB, select and remove an entry from the list (see array_shift) and put the list back in the DB. You do this until there are no more video keys, then fire the google query again and so on... This saves your script from querying Google on each page load, and decreases the chances for being redirected to the same video

Upvotes: 3

amigura
amigura

Reputation: 539

$i=0; $random_video = mt_rand(1, 25);

  $sxml = simplexml_load_file("http://gdata.youtube.com/feeds/api/users/TechTubeCentral/uploads?max-results=25");
foreach ($sxml->entry as $entry) {

    if($random_video==$i++){
  $vidKey = substr(strrchr($entry->id,'/'),1); break;
    }
}

Upvotes: 0

Related Questions