按高度对图像数组进行排序


PHP - Sort array of images by height

取以下;

// Looping through images passed to function...
list($width[$i], $height[$i]) = getimagesize($img_urls[$i]);
// ... Now to reorder by height

如何将$height数组重新排序为最高>最短,同时保持与正确的$width值的键关系?

我尝试用uasort,但我没有运气。我做过的"最接近"的尝试如下,但它从最小到最大排序

uasort($height, function($a, $b) use ($i) {
    return $a[$i] + $b[$i];
});

首先,使用结构:

class Image {
    public $width;
    public $height;
}

这是必要的,因为图像的宽度和高度几乎没有联系。没有图像的高度,一个图像的宽度显示不出任何东西。身高也是一样。你应该把这些数据联系起来。例如,在结构。

之后,获取图像高度和宽度:

$images = array();
// get widths and heights
loop start
    $img = new Image();
    $img->width = assign width;
    $img->height = assign height;
    $images[] = $img;
loop end

最后,排序:

function cmp($a, $b) {
    if ($a->height == $b->height) {
        return 0;
    }
    return ($a->height < $b->height) ? -1 : 1;
}
uasort($images, 'cmp');
//$images are sorted by height now

试试这个:

$images = array();
for ($i = 0; $i < count($img_urls); $i++) {
    $image_size = getimagesize($img_urls[$i]);
    $images[$image_size[1]]['width'] = $image_size[0];
    $images[$image_size[1]]['height'] = $image_size[1];
}
sort($images);
var_dump($images);

usasort应该可以正常工作:

uasort( $height, function ( $a, $b ) { if ( $a == 0 ) { return 0; } else { return ( $a > $b ) ? -1 : 1; } } );

如果我这样做:

$arr = array();
$arr[0] = 512;
$arr[1] = 1024;
uasort( $arr, function ( $a, $b ) { if ( $a == 0 ) { return 0; } else { return ( $a > $b ) ? -1 : 1; } } );
var_dump( $arr );
var_dump( $arr[0] );
var_dump( $arr[1] );

:

array(2) {
  [1]=>
  int(1024)
  [0]=>
  int(512)
}
int(512)
int(1024)