Jump to content

Need help with random text script


sparkbark

Recommended Posts

hello,

i want to use a script that will call up random text files for insertion in a webpage, which is easy enough, but the important thing is that it needs to cycle through all of the text files in the directory first before it repeats any of them. is this possible? how would i go about modifying a regular 'random text file' script into one that will behave this way?

Link to comment
Share on other sites

You would have to take your standard text randomizer, and use something like cookies or a session to hold the values of the text that has already been output. I believe this would only work if the page refreshed each time, because I do not know if cookies/sessions can be used with ajax. I had a nice javascript text randomizer on my site, and I always wanted this functionality you desire, but never got around to implementing it. Please post your final code when you figure it out.

Link to comment
Share on other sites

yes cookies/sessions would be helpful, however ajax can have a solution

 

The ajax solution:

 

1) Set up a mysql table with the list of lines and a primary key of textID

2) Set up a table called temp_viewed with a primary key of SessionID, and fields of all the textIDs from the first table

3) Set an intial session on loading, store this sessionID in the mysql table in part 2

4) In your ajax area of the page run a query that says get all the textIDs from 2 that this sessionID id  has not viewed, put them in ($array) array and count

4b) after that generate a random number from 0 to the count-1 of the above mentioned array call it $random_id

5) query table in part 1 for $array($random_id) and display it

5b) Update the table in 2 to reflect that this ID has been viewed.

6) Enjoy

 

and for clean up you can add an IP address to that table on the initial session creation say, if the same ip has another row delete it cause its pointless.  Also you can probably get a cron job to delete old entries once a week, or just do a full flush on the table as its not terribly crucial data.

 

Make sense?

 

Link to comment
Share on other sites

I was bored, so I made this, and it does work, but can probably be refined or changed to suit your needs:

 

<?php
session_start();
echo count($_SESSION['randomNums']) . "<br>";
print_r($_SESSION['randomNums']);
function randomNoRepeat(){
$max= 6;
$num = Rand (1,$max);
if(isset($_SESSION['randomNums']) && in_array($num,$_SESSION['randomNums'])){
	if (count($_SESSION['randomNums']) == 6){
		switch ($num)
		{
		case 1:
		echo "Time is money";
		break;
		case 2:
		echo "An apple a day keeps the doctor away";
		break;
		case 3:
		echo "Elmo loves dorthy";
		break;
		case 4:
		echo "Off to see the wizard";
		break;
		case 5:
		echo "Tomorrow is another day";
		break;
		case 6:
		echo "PHP is cool!";
		}
		unset($_SESSION['randomNums']);
	}else{
		randomNoRepeat();
	}
}else{
	switch ($num)
	{
	case 1:
	echo "Time is money";
	$_SESSION[randomNums][] = $num;
	break;
	case 2:
	echo "An apple a day keeps the doctor away";
	$_SESSION[randomNums][] = $num;
	break;
	case 3:
	echo "Elmo loves dorthy";
	$_SESSION[randomNums][] = $num;
	break;
	case 4:
	echo "Off to see the wizard";
	$_SESSION[randomNums][] = $num;
	break;
	case 5:
	echo "Tomorrow is another day";
	$_SESSION[randomNums][] = $num;
	break;
	case 6:
	echo "PHP is cool!";
	$_SESSION[randomNums][] = $num;
	}
}
}
randomNoRepeat();
?>

Link to comment
Share on other sites

Yeah I think the better idea instead of running a possible infintinte loop would be to first have the full set of all possible things, then subtract from that the list of ones used, put those in a single array and then generate a random value from that and that is your given string key. such as  (note I am using mysql vs sessions to store as if you get a lot of strigns it will bog down your server

<?php
session_start();
$strings = array("Text1", "Text2", "Text3", "Text 4");
$num_items = count($strings); //Should return 4 in this case
connectSQL(); //Connect to sql and pick your db
$s_id = session_id();
$q = "Select String_ID From `temp_data` Where Session_id = '".$s_id."' Order by String_ID";
$r = mysql_query($q) or die(mysql_error());
$used_strings = array();
while($row = mysql_fetch_assoc($r)){
$used_strings[] = $row['String_ID'];
}
//Now we need to use what is used to what is not used
$unused_strings =  array();
for($i=0; $i<=$num_items; $i++){
//If that counting number $i is  not equal to that given array value, then we know that string is open for use
if($i != $used_strings[$i]){
$unused_strings[] = $used_strings[$i];
}
}

$picked_string = array_rand($unused_strings);

echo $strings[$picked_string];

//Now we need mysql to reflect this so we say
$q = "Insert into `temp_data` fields(Session_ID, String_id) Value ('".$s_id."', '".$picked_string."')";
$r = mysql_query($q) or die(mysql_error());
?>

 

You could use the above in ajaxs, you just need ajaxs to do all of the above, but echo it out in a different fashion.

 

Also note how I don't care if the mysql result is 0 rows, this is because the array $used_strings will result in 0 items and you will have any string open to use, yes you could test for it, but what is the point.

Link to comment
Share on other sites

Here is another way you can do it, which is more convenient, because you can store all the text to be randomized in an array:

<?php
session_start();
function randomNoRepeat(){
include ('randomText.inc');
$max = count($arr);
$num = Rand (0,($max-1));
if(isset($_SESSION['randomNums']) && in_array($num,$_SESSION['randomNums'])){
	if (count($_SESSION['randomNums']) == $max){
		echo $arr[$num];
		unset($_SESSION['randomNums']);
	}else{
		randomNoRepeat();
	}
}else{
	echo $arr[$num];
	$_SESSION[randomNums][] = $num;
}
}
randomNoRepeat();
?>

 

 

Here is the include file I used that has the array in it:

<?php
$arr = array(	'I like tacos.',
	'Becky loves to work at my store.',
	'My brother is finally moving out!',
	'I gotta get back to work.',
	'Old ladies always have problems.'
	);
?>

Link to comment
Share on other sites

hi all,

thanks for the answers. however, i should have specified that these need to be text FILES, not just sentences. they will be multiple paragraphs each. so the script needs to call seperate files for display.

 

i also am just starting with php and i don't understand half of this... sorry :(

Link to comment
Share on other sites

You are going to have to learn php for an explaination, but here is some code that will do what you want with files:

 

<?php
session_start();
function randomNoRepeat(){
include ('randomTextFiles.inc');
$max = count($arr);
$num = Rand (0,($max-1));
if(isset($_SESSION['randomNums']) && in_array($num,$_SESSION['randomNums'])){
	if (count($_SESSION['randomNums']) == $max){
		$fileNum = $arr[$num];
		$handle = file($fileNum);
		foreach ($handle as $line_num => $line) {
		echo $line;
		}
		unset($_SESSION['randomNums']);
	}else{
		randomNoRepeat();
	}
}else{
	$fileNum = $arr[$num];
	$handle = file($fileNum);
	foreach ($handle as $line_num => $line) {
	echo $line;
	}
	$_SESSION[randomNums][] = $num;
}
}
randomNoRepeat();
?>

 

And here is the include file with the names of the files you want to output. You didn't say what kind of files these are, so they may require some formatting to output the way you want.

 

<?php
$arr = array(	'file_a.txt',
	'file_b.txt',
	'file_c.txt',
	'file_d.txt',
	'file_e.txt'
	);
?>

Link to comment
Share on other sites

you could have a counter for execution and keep the actualy number stores in a database or flat file, and have it read that and basicaly add one each time.

 

and if you have say 6 files you want to cycle through, you simply add an if scenario that recycles back to 1 after the 6 have been shown

 

similair to below (not actual code)

 

retreive database number

execute database number

I++ database number

if number equals 7 (if you have 6 files assign value of 1)

store back into database

 

you'd need a database table or flat file as I said but that wouldn't be too hard if you've worked with them at all, I'll the actual code if needed but it's not really that complicated

Link to comment
Share on other sites

wait, now it has started repeating entries before it has gone through them all. i cleared my cache, cookies, etc and tried again and it still is broken

 

Maybe somebody can point out what is wrong with my script. It may be easier to fix it at this point, but I'm at work and can't spend time on it right now.

Link to comment
Share on other sites

try

<?php
session_start();

//1st generat $array_text_files with all text files in it
$a_text_files = array('one','two' ,'sasa','angelina', 75, 'is it works?');

if (!array_key_exists('rand_text_files', $_SESSION)) $_SESSION['rand_text_files'] = $a_text_files;
if (count($_SESSION['rand_text_files']) == 0) $_SESSION['rand_text_files'] = $a_text_files;
shuffle($_SESSION['rand_text_files']);
$rand_text = $_SESSION['rand_text_files'][0]; //
unset($_SESSION['rand_text_files'][0]); //prevent repeats

// do what you want with $rand_text
echo $rand_text;

?>

Link to comment
Share on other sites

Nice code sasa! It's amazing the way that different people will try to solve the same problem.

 

Check this out sparkbark:

 

<?php
session_start();
include('sasa_array.inc');
if (!array_key_exists('rand_text_files', $_SESSION)) $_SESSION['rand_text_files'] = $a_text_files;
if (count($_SESSION['rand_text_files']) == 0) $_SESSION['rand_text_files'] = $a_text_files;
shuffle($_SESSION['rand_text_files']);
$rand_text = $_SESSION['rand_text_files'][0];
unset($_SESSION['rand_text_files'][0]);
$handle = file($rand_text);
foreach ($handle as $line_num => $line) {
echo $line;
}
?>

 

The array of files in sasa_array.inc:

<?php
$a_text_files = array(	'file_a.txt',
	        'file_b.txt' ,
	        'file_c.txt',
	        'file_d.txt',
	        'file_e.txt'
	        );
?>

Link to comment
Share on other sites

I have to agree nice code sasa.

 

you are remember to put the top block of code at the top right, session does work with cookies, so it'll have to go before any output is sent to the browser unless your using output buffering, which is a great thing to use anyhow.

 

sasa's code is fine, I've actually tested it myself, it must be a bug in your code somewhere, or an incompatibility somewhere

Link to comment
Share on other sites

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.