Jump to content

Recommended Posts

hello everyone

 

here is some code i got to display random items from a txt file.

 

[pre]<?php

 

// load the file that contain the ads

$adfile = "ads.txt";

$ads = array();

 

// one line per ad

$fh = fopen($adfile, "r");

while(!feof($fh)) {

 

  $line = fgets($fh, 10240);

  $line = trim($line);

  if($line != "") {

$ads[] = $line;

  }

}

 

// randomly pick an ad

$num = count($ads);

$idx = rand(0, $num-1);

 

echo $ads[$idx];

?>[/pre]

 

Could someone tell me how i could make it show more than 1 item at a time. Like 10 links from the ads.txt file would be great.

 

Thanks you all in advance  :)

put code into code tags please when the code is more than one line (or even then if you'd like)

[ code ]code goes here[ /code ] remove the spaces in between [] on the tags:

code goes here

 

<?php

// load the file that contain the ads
$adfile = "ads.txt";
$ads = array();

// one line per ad
$fh = fopen($adfile, "r");
while(!feof($fh)) {

  $line = fgets($fh, 10240);
  $line = trim($line);
  if($line != "") {
   $ads[] = $line;
  }
}

// randomly pick an ad
$i=0;
while($i < 10){
  $num = count($ads);
  $idx = rand(0, $num-1);
  echo $ads[$idx];
  $i++;
}
?>

Try that, should do it 10 times.

try this

 

change:

$ads[] = $line;

 

to:

$ads[] .= $line;

 

mmm not really...

 

<?php

// load the file that contain the ads
$adfile = "ads.txt";
$ads = array();

// one line per ad
$fh = fopen($adfile, "r");
while(!feof($fh)) {

  $line = fgets($fh, 10240);
  $line = trim($line);
  if($line != "") {
   $ads[] = $line;
  }
}

// randomly pick an ad
$num = count($ads);
$idx = array();
while (count($idx) != 10) { 
    $rand = rand(0, $num-1);
    if (!in_array($rand, $idx)) 
        $idx[] = $rand;
}

foreach ($idx as $id) 
    echo $ads[$id] . "<br />";
?>

 

Something like that would work, this assumes you have more than 10 items in that list, and with the random, the scripts execute time will vary.

 

EDIT:

The difference between this one and Brians, is that the one I posted should guarantee 10 unique ads, Brian's may not. But yea, whichever one better suits your needs.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.