Michdd Posted March 30, 2009 Share Posted March 30, 2009 I want to loop through a directory and I need to get the name of a file at a certain place. my files are named like this: bitmap_2, bitmap_3, bitmap_4, etc.. The only problem is when I loop through the directory it doesn't go through in the correct order. It goes like... Bitmap_10.bmpBitmap_100.bmpBitmap_101.bmpBitmap_102.bmpBitmap_103.bmpBitmap_104.bmpBitmap_105.bmpBitmap_106.bmpBitmap_107.bmpBitmap_108.bmpBitmap_109.bmpBitmap_11.bmpBitmap_110.bmpBitmap_111.bmpBitmap_112.bmp Is there any way I can get it to loop through in the correct order so I can get an accurate result? Link to comment https://forums.phpfreaks.com/topic/151684-looping-through-a-directory-in-a-certain-order/ Share on other sites More sharing options...
corbin Posted March 30, 2009 Share Posted March 30, 2009 That's technically alphabetical. (Alphabetically 10 is before 100, and 101 is before 11. It's just like ba is before baa, and bab is before bb.) You could parse out the number and order it based on that. Or, you could pad the names with 0s. Bitmap_010.bmp for example. Link to comment https://forums.phpfreaks.com/topic/151684-looping-through-a-directory-in-a-certain-order/#findComment-796563 Share on other sites More sharing options...
Michdd Posted March 30, 2009 Author Share Posted March 30, 2009 That's technically alphabetical. (Alphabetically 10 is before 100, and 101 is before 11. It's just like ba is before baa, and bab is before bb.) You could parse out the number and order it based on that. Or, you could pad the names with 0s. Bitmap_010.bmp for example. How would I write a script that would rename the files so it would order correctly for me? So I don't have to rename 120 files just to get this to work.. Link to comment https://forums.phpfreaks.com/topic/151684-looping-through-a-directory-in-a-certain-order/#findComment-796567 Share on other sites More sharing options...
corbin Posted March 30, 2009 Share Posted March 30, 2009 Hrmmm, not tested: <?php $imgs = glob('*.bmp'); $nofi = count($imgs); $digits = strlen($nofi); $format = "%0{$digits}d"; foreach($imgs as $name) { if(preg_match('/Bitmap_(\d+)\.bmp/', $name, $m)) { $number = printf($format, $m[1]); copy($name, "Bitmap_{$number}.bmp"); } } I went with copy() just incase I coded something wrong ;p. Link to comment https://forums.phpfreaks.com/topic/151684-looping-through-a-directory-in-a-certain-order/#findComment-796574 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.