php - Sort array based on the numbers and a certain piece of text that occurs within a string -


i have array got directory pdf files in using scandir

$array = array(7) {      [0]=> string(17) "q150824-spost.pdf"      [1]=> string(17) "s150826-spost.pdf"      [2]=> string(16) "s150826-spro.pdf"      [3]=> string(17) "t150827-spost.pdf"      [4]=> string(16) "t150827-spro.pdf"      [5]=> string(17) "v150825-spost.pdf"      [6]=> string(16) "v150825-spro.pdf"  } 

i need sort array numbers in file name (eg. 150824 date) can using following:

usort($array, function($a, $b) {   return filter_var($a, filter_sanitize_number_int) - filter_var($b, filter_sanitize_number_int); }); 

the above gives me array sorted numbers (which want):

$array = array(7) {      [0]=> string(17) "q150824-spost.pdf"      [1]=> string(17) "v150825-spost.pdf"      [2]=> string(16) "v150825-spro.pdf"      [3]=> string(16) "s150826-spro.pdf"      [4]=> string(17) "s150826-spost.pdf"      [5]=> string(17) "t150827-spost.pdf"      [6]=> string(16) "t150827-spro.pdf"  } 

however, in addition sort alphabetically spost , spro (the text before .pdf) i'm @ loss how achieve though?

if 2 strings in array have same numbers/date (eg. 150826) want sort spost first , spro.

this should work you:

first grab number , topic name out of file name preg_match_all() , assign variables. after sort topic, if numbers equal, otherwise numbers.

<?php       usort($arr, function($a, $b){         preg_match_all("/^\w(\d+)-(\w+)/", $a, $ma);         preg_match_all("/^\w(\d+)-(\w+)/", $b, $mb);          $numbera = $ma[1][0];         $numberb = $mb[1][0];          $topica = $ma[2][0];         $topicb = $mb[2][0];          if($numbera == $numberb){             return strcmp($topica, $topicb);         }          return $numbera > $numberb ? 1 : -1;      });       print_r($arr);  ?> 

output:

array (     [0] => q150824-spost.pdf     [1] => v150825-spost.pdf     [2] => v150825-spro.pdf     [3] => s150826-spost.pdf     [4] => s150826-spro.pdf     [5] => t150827-spost.pdf     [6] => t150827-spro.pdf ) 

Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -