Jump to content

Looping through a directory in a certain order?


Michdd

Recommended Posts

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?

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.

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..

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.