Jump to content

[SOLVED] Need some help to make work right.


Janik

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.