Jump to content

[SOLVED] Sorting sentences alphanumerically?


gamefreak13

Recommended Posts

I have hundreds of sentences (one per line) and need to sort them all alphabetically and numerically. And not just for the first letter.. I want it to sort it as far as possible.

 

Example input:

 

What was the last drink you had?
What was the last movie you watched?
What was the last 11.. just inserting a number here as an example?
What was the last book you read?

 

Example output:

 

What was the last 11.. just inserting a number here as an example?
What was the last book you read?
What was the last drink you had?
What was the last movie you watched?

 

This is my code I am using right now to read my text file and output it on my page (which is formatted as a MySQL INSERT query).

 

<?php

$file = "sentences.txt";
$fp = fopen($file, "r");
$data = fread($fp, filesize($file));
fclose($fp);

$output = explode("\n", $data);

foreach($output as $var) {

if($var == "") {
	echo "<br>";
} else {
	echo "INSERT INTO survey SET question='$var';<br>";
}

}

echo "Done!";

?>

Can you be a little more specific?

 

I added this under $output = explode... and I get "Warning: Invalid argument supplied for foreach() in readtxt.php on line 17".

 

sort($output);
foreach($output as $key => $val) {
    $output = "output[" . $key . "] = " . $val . "\n";
}

that's because inside your foreach statement you're reassigning something to $output (that's not an array)

 

this works fine:

<?php

$file = "sentences.txt";
$fp = fopen($file, "r");
$data = fread($fp, filesize($file));
fclose($fp);

$output = explode("\n", $data);
sort($output);
foreach($output as $var) {
   if($var == "") {
      echo "<br>";
   } else {
      echo "INSERT INTO survey SET question='$var';<br>";
   }
}
echo "Done!";

?>

 

it outputs:

INSERT INTO survey SET question='What was the last 11.. just inserting a number here as an example?';
INSERT INTO survey SET question='What was the last book you read?';
INSERT INTO survey SET question='What was the last drink you had?';
INSERT INTO survey SET question='What was the last movie you watched?';
Done!

Thanks.. I tried adding just the sort part and it worked but I didn't realize it because it outputted a bunch of empty lines so the page appeared to be blank to me. I tried it again after reading your post and noticed the scrollbar. Doh!

 

Thanks! :)

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.