php - Array isn't sorting when writing to file -


i wrote script:

<?php $file_handle = fopen("info.txt", "rb"); while (!feof($file_handle) ) {     $line_of_text = fgets($file_handle);     $parts[] = explode('|', $line_of_text); }  fclose($file_handle); $a = $parts;  function cmp($a,$b){     return strtotime($a[8])<strtotime($b[8])?1:-1; };  uasort($a, 'cmp'); $failas = "dinfo.txt"; $fh = fopen($failas, 'w');  for($i=0; $i<count($a); $i++){     $txt=implode('|', $a[$i]);     fwrite($fh, $txt); } fclose($fh); ?> 

when use:

print_r($a); 

after

uasort($a, 'cmp'); 

then can see sorted array. when write file using these commands:

$fh=fopen($failas, 'w'); for($i=0; $i<count($a); $i++){     $txt=implode('|', $a[$i]);     fwrite($fh, $txt); } fclose($fh); 

it shows not sorted information, doing wrong?

this should work you:

here first file array file() every line 1 array element. there ignore empty lines , new line characters @ end of each line.

after sort array usort(). first dates , times each line explode()'ing it. after timestamp of each date strtotime() , compare each other.

at end save file file_put_contents(), add new line character @ end of each line array_map().

<?php      $lines = file("test.txt", file_skip_empty_lines | file_ignore_new_lines);      usort($lines, function($a, $b){         list($adate, $atime) = explode(" ", explode("|", $a)[substr_count($a, "|")]);         list($bdate, $btime) = explode(" ", explode("|", $b)[substr_count($b, "|")]);          if(strtotime("$adate $atime") == strtotime("$bdate $btime"))             return 0;         return strtotime("$adate $atime") < strtotime("$bdate $btime") ? 1 : -1;     });      file_put_contents("test.txt", array_map(function($v){return $v . php_eol;}, $lines));  ?> 

side notes:

i recommend save data in database flexible sort , getting data!

edit:

for people have php version (echo phpversion();) under <5.3, change anonymous functions normal functions , pass function name strings this:

<?php      $lines = file("test.txt", file_skip_empty_lines | file_ignore_new_lines);      function timestampcmp($a, $b) {         $aexploded = explode("|", $a);         $bexploded = explode("|", $b);          list($adate, $atime) = explode(" ", $aexploded[substr_count($a, "|")]);         list($bdate, $btime) = explode(" ", $bexploded[substr_count($b, "|")]);          if(strtotime("$adate $atime") == strtotime("$bdate $btime"))             return 0;         return strtotime("$adate $atime") < strtotime("$bdate $btime") ? 1 : -1;      }      function addendline($v) {         return $v . php_eol;     }      usort($lines, "timestampcmp");      file_put_contents("test.txt", array_map("addendline", $lines));  ?> 

Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -