How to randomize order of lines? [SOLVED]
Posted: Thu Feb 03, 2005 3:50 pm
There is one "keyword" file (keywords.txt)with this content:
keyword 1
keyword 2
keyword 3
keyword 4
keyword 5
keyword 6
I want to randomize the order of each of the "keywords" so that the output looks something like for example (file name: random_kws.txt):
keyword 2
keyword 1
keyword 4
keyword 3
keyword 6
keyword 5
I tried this code:
This code does indeed randomize the order, but not properly. It lists some of the keywords multiple times while others not all. The point is, each of the keywords/lines should be in the random list, just in a random order on each script run.
Any ideas are welcome!
Tomas
keyword 1
keyword 2
keyword 3
keyword 4
keyword 5
keyword 6
I want to randomize the order of each of the "keywords" so that the output looks something like for example (file name: random_kws.txt):
keyword 2
keyword 1
keyword 4
keyword 3
keyword 6
keyword 5
I tried this code:
Code: Select all
<?php
function file_write_data($filename, $file_body, $chmod=0777, $mode='w'){
$handle = fopen($filename, $mode);
fwrite($handle, $file_body);
fclose($handle);
chmod ($filename, $chmod);
return $file_body;
}
$keyword_file = 'keywords.txt';
$keywords = file_get_contents($keyword_file);
$keywords = explode("\n", $keywords);
$lines_count = count($keywords);
for($n=0; $n<=$lines_count-1; $n++){
$random_kw = mt_rand(0, $lines_count-1);
$Terms = $keywordsї$random_kw];
$AllKeywords .= "$Terms\n";
}
file_write_data('random_kws.txt', $AllKeywords, 0777);
$FileArr = file('random_kws.txt');
$FilteredArr = array("a\n\r", "\n\r", "\n\r", "b\n\r");
$FilteredArr = array_map('trim', $FileArr);
$FilteredArr = array_filter($FilteredArr);
$FilteredArr = array_unique($FilteredArr);
$FilteredArr = array_values($FilteredArr);
sort($FilteredArr);
reset($FilteredArr);
$kw_count = count($FilteredArr);
echo file_get_contents('random_kws.txt');
?>Any ideas are welcome!
Tomas