I am trying to sort a flat file (.txt) in descending order.
Here's the list inside file.txt (name, age, ID No.) :
Jason, 24, 18299
Bryan, 19, 12999
James, 32, 72990
My goal is to arrange the list in descending natural order based on the second column. I tried making a natrsort function to reverse the arrangement.
Here's what i came up with:
<?php
$rows = array();
$result = '';
$data = file('file.txt');
function natrsort(&$array) //the function i made to arrange them in descending order
{
natsort($array);
$array = array_reverse($array);
}
foreach($data as $key => $val) {
$rowarray = explode(",", $val);
$rows[] = $rowarray[1];
}
natrsort($rows);
//print_r($rows); When I use this, everything seems to work.
foreach($rows as $key => $val) {
$result .= trim($data[$key]) . "<br/>";
}
echo $result; //display the new sorted list
The output keeps displaying the same list. No Sorting happened. Maybe I am missing something?
When you use
$data[$key],$keyis equals to0,1and2, becausearray_reverse()re-index the array. So, your printed array is in the same order than your data in the file.You could use
natsort(), then, reverse the array of keys only:Prints:
Another way is to sort using a custom sort function like
usort():Output: