syntonik syntonik - 6 months ago 19
PHP Question

Re-sort a list in a text file in PHP

everyone. Very first question, so take it easy on this noob. ;)

Anyway, really stumped on something. I've got a text file with this sort of listing:

1: A C D
4: A B
5: D F
7: A E
9: B C


The goal is to somehow re-sort this list and have it appear as this:


A: 1 4 7
B: 4 9
C: 1 9
D: 1 5
E: 7
F: 5


The trick is matching and displaying those matched values. For example "A" is matched with lines 1,4 and 7, and so on. I can explode the lines into individual arrays, but after that stumps me. How would I go about taking those arrays and somehow sorting them out to make it look like the final version?

Thanks for any and all info!

UPDATE:

Code I have so far:

<?php
$string="1: A C D
4: A B
5: D F
7: A E
9: B C";
$lines = explode( "\n", $string );
sort($lines);
foreach($lines as $line){
echo $line."<br>";
}

// start with this
//1: A C D
//4: A B
//5: D F
//7: A E
//9: B C

// resort and display as this
//A: 1 4 7
//B: 4 9
//C: 1 9
//D: 1 5
//E: 7
//F: 5
?>


Which produces:


1: A C D
4: A B
5: D F
7: A E
9: B C


Right now I don't care that they are not in new lines. That's not important at the moment. Right now, I need to figure out how to make it sort and appear as the 2nd code block. That is the part that puzzles me.

Hope this helps clear up things.

Answer

Well, you sort of gave it a try and I was bored:

//read file into array of lines
$lines = file('/path/to/file.txt', FILE_IGNORE_NEW_LINES);

//loop through the lines
foreach($lines as $line) {
    //explode on space
    $cols = explode(' ', $line);
    //loop through columns and build array with letter as key adding number to that array
    for($i=1; $i < count($cols); $i++) {
        $result[$cols[$i]][] = trim($cols[0], ':');
    }
}
//sort by key (or sort $output later)
ksort($result);

//loop through and build new lines
foreach($result as $key => $vals) {
    $output[] = "{$key}: " . implode(' ', $vals);
}
//write lines to file
file_put_contents('/path/to/file.txt', implode("\n", $output));
Comments