0

Reading from a flatfile... I need to display array elements sorted by DESCENDING date (= most current date displays first).

Not sure... Is there a way to simply sort the data by element[1] or do I need to put this data into a second array and then sort that array... or ??

Then... PLEASE include the print section... the variables necessary to output the data. Thanks.

(*Yes, I have seen some other examples of this on 'stack.' However, I have not been able to output the values correctly when using the 'compare.')

RAW DATA:
yes|2012-12-12|Jim None
yes|2013-06-04|Joe Smith
no|2013-04-21|Jane Doe

SORTED DATA:
yes|2013-06-04|Joe Smith
no|2013-04-21|Jane Doe
yes|2012-12-12|Jim None

while (!feof($file) ) {
    $lines = fgets($file);
    $ele = explode('|', $lines);

    $db_display = $ele[0];
    $db_date = $ele[1];
    $db_name = $ele[2];

    $db_name = substr_replace($db_name,"",-1); // trim last char

    echo '<td>'.$db_name.'</td><td>'.$db_date.'</td>';
}
mar2195
  • 103
  • 1
  • 10

2 Answers2

1

This should get you there...

Assuming you are getting from a file name $infile

$fp = fopen($infile, "w");
$data = array();
while ($rec = fgetcsv($fp, 2048, "|")){
         $data[] = $rec;
}


usort($data, function ($a, $b){
     // if you want to reverse the sort swap a for b
     return strtotime($b[1]) - strtotime($a[1]);
});



foreach($data as $v){
   echo implode("|", $v)."\n";
}

Ouput to standard out ... you can just as easily fopen/fputcsv the same data.

Orangepill
  • 24,500
  • 3
  • 42
  • 63
  • Thanks. Question: Can you please post the WHILE section using the coding syntax from my original posting? (FYI: $file in my code is your $fp) – mar2195 Jun 07 '13 at 04:51
  • can't use your loop because you have to accumulate the values prior to sorting. but the updated code should basically be a drop in replacement for you have posted in the answer. – Orangepill Jun 07 '13 at 04:58
  • Yep. You're right. For future reference for others, please post your first coding solution. That's the one that works. One more thing... How would I EXPLODE the date in the FOREACH to divide the date into MO, DT, YR? – mar2195 Jun 07 '13 at 05:25
  • Rolled it back ... simplest way to explode would be `list($yr, $mo, $dt) = explode("-", $b[1]);` – Orangepill Jun 07 '13 at 05:32
  • Sorry for the newbie questions... Where the heck do I put the "list / explode" line of code? – mar2195 Jun 07 '13 at 05:52
  • if you are wanting to do it in the output it would be in the foreach block on the bottom which I think in all versions that I had posted was $v[1] not $b[1]; Then you can echo it where needed. If you just want to display the date in a different format you can skip the split business and just use `date('F j, Y', strtotime($v[1]));` see [here](http://php.net/manual/en/function.date.php) for format options. – Orangepill Jun 07 '13 at 05:58
0
usort($array, function($x, $y) { 
    return strcmp($y[1], $x[1]);
});
Barmar
  • 741,623
  • 53
  • 500
  • 612