Home > Blockchain >  natrsort function not returning values
natrsort function not returning values

Time:02-13

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?

CodePudding user response:

When you use $data[$key], $key is equals to 0,1 and 2, because array_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:

natsort($rows);
$indexes = array_reverse(array_keys($rows));
foreach ($indexes as $key) {
    $result .= trim($data[$key]) . '<br>';
}

Prints:

James, 32, 72990<br>Jason, 24, 18299<br>Bryan, 19, 12999<br>

Another way is to sort using a custom sort function like usort():

$result = '';
$data   = file('file.txt');

usort($data, function($a, $b) {
   [, $ageA] = explode(',', $a);
   [, $ageB] = explode(',', $b);
   return intval($ageB) <=> intval($ageA);
});

foreach ($data as $val) {
    $result .= trim($val) . '<br>';
}
echo $result;

Output:

James, 32, 72990<br>Jason, 24, 18299<br>Bryan, 19, 12999<br>
  • Related