Sorting an array of directory filenames in descending natural order

前端 未结 3 1416
没有蜡笔的小新
没有蜡笔的小新 2021-01-25 09:06

I have a content directory to be returned in descending natural order.

I\'m using scandir() and natsort(), but the addition of array_reve

3条回答
  •  别那么骄傲
    2021-01-25 09:46

    If your image names will be in the format 123-image_name.jpg, 2323-image_name.jpg, ... this will do:

    /**
     * Compares digits in image names in the format "123-image_name.jpg"
     *
     * @param string $img1 First image name
     * @param string $img2 Second image name
     * @return integer -1 If first image name digit is greater than second one.
     * 0 If image name digits are equal.
     * 1 If first image name digit is smaller than second one.
     */
    function compareImageNames($img1, $img2){
        $ptr = '/^(\d+)-/'; // pattern
    
        // let's get the number out of the image names
        if (preg_match($ptr, $img1, $m1) && preg_match($ptr, $img2, $m2)) {
            $first  = (int) $m1[0]; // first match integer
            $second = (int) $m2[0]; // second match integer
    
            // equal don't change places
            if($first === $second) return 0;
    
            // if move first down if it is lower than second
            return ($first < $second) ? 1 : -1;
        } else{
            // image names didn't have a digit in them
            // move them to front
            return 1;
        }
    }
    
    // sort array
    usort($images, 'compareImageNames');
    

提交回复
热议问题