Reputation: 329
I have a file that I'm trying to write a string to, and want to do so based in alphabetical order but am unsure how to do it.
I can open the file, which has a huge list (example below) of how the files are arranged, first in alphabetical order by their sections and then by their filenames.
What I would like and am trying to do in my php script is open the file, search alphabetically based on the second word /section/
then by the third /filename=1
and insert the string in the proper order.
I already know how to open the file and append the string at the bottom but have no clue how to search alphabetically and if its even possible (though of course it is, at least I think). I'm reading through tons of answers and php manuals and perhaps I'm too tired but I'm missing it.
rooms/creative/thelastofus=1
rooms/creative/thetombs=1
rooms/creative/varekai=1
rooms/erotic/denofdecadence=1
rooms/erotic/dungeon=1
rooms/fantasy/americangods=1
rooms/fantasy/arvandor=1
rooms/gorean/aldushara=1
rooms/gorean/grpexplorations=1
rooms/history/blackethornebluff=1
rooms/history/sandsoftime=1
rooms/supernatural/ahsgenocide=1
rooms/supernatural/ahspurgatory=0
rooms/reality/grafica=1
So basically I need it to open the file, search alphabetically. Then insert the string rooms/section/filename=1
in the right order.
I would be eternally grateful for any pointers in the right direction.
Upvotes: 1
Views: 199
Reputation: 11084
This is how you would use a user-defined sort to sort the files by folder and filename. In my testing comparing strings with "<" worked as expected.
$arr = ['rooms/creative/thelastofus=1'
,'rooms/fantasy/americangods=1'
,'rooms/fantasy/arvandor=1'
,'rooms/creative/thetombs=1'
,'rooms/creative/varekai=1'
,'rooms/erotic/denofdecadence=1'
,'rooms/erotic/dungeon=1'
,'rooms/gorean/aldushara=1'
,'rooms/gorean/grpexplorations=1'
];
print_r($arr);
uasort($arr, function($a,$b){
$splitA = explode('/',$a);
$splitB = explode('/',$b);
if( $splitA[1] == $splitB[1] ){
//Compare filenames
if( $splitA[2] == $splitB[2] ){
return 0;
}
else{
return $splitA[2] < $splitB[2] ? -1 : 1;
}
}
else{
return $splitA[1] < $splitB[1] ? -1 : 1;
}
});
print_r($arr);
Upvotes: 2
Reputation: 369
You can put each line in an array and then just sort them like this:
$testArray = sort($testArray);
It will sort it in alphabetical order. Then you can do whatever you want to it. Loop it into a string to output. Or compare for instance.
See this if you could use some more info on the subject: http://www.w3schools.com/php/func_array_sort.asp
Upvotes: 4