PHP按最大宽度和宽度大于高度的地方对图片进行排序

Posted

技术标签:

【中文标题】PHP按最大宽度和宽度大于高度的地方对图片进行排序【英文标题】:PHP Sort pictures by biggest width and where width is bigger than height 【发布时间】:2016-01-31 03:20:22 【问题描述】:

我有一个这样的数组:

 array(
    0 => array(
       width => "213",
       height => "50"
    ),
    1 => array(
       width => "120",
       height => "204"
    )
 ) etc...

现在我想按宽度值最大且宽度大于高度的图片来排序这个数组。

我的尝试是,使用usort():

usort($results['bos-s-response']['images']['results'], function($a, $b)  
            return $b['width'] - $a['width'];
);

但它只是根据图片的宽度对图片进行排序,而不是图片的宽度大于高度。用 usort 可以吗?

【问题讨论】:

【参考方案1】:

试试这个:

usort($results['bos-s-response']['images']['results'], function($a, $b)  
    //Case if A has bigger width than height but B doesn't
    if($a["width"]>$a["height"] && !($b["width"]>$b["height"])) return -1;

    //Case if B has bigger width than height but A doesn't
    if(!($a["width"]>$a["height"]) && $b["width"]>$b["height"]) return 1;

    //They both/neither have bigger width than height, so compare widths
    if($a["width"]>$b["width"]) return -1;
        elseif($b["width"]>$a["width"]) return 1;
        else return 0;
);

【讨论】:

以上是关于PHP按最大宽度和宽度大于高度的地方对图片进行排序的主要内容,如果未能解决你的问题,请参考以下文章

ImageView最大高度和宽度失效解决方案

CSS3如何固定图片宽度使图片高度按图片比例自适应?

如何用PHP输出图片的宽度和高度?

CSS3如何固定图片宽度使图片高度按图片比例自适应?

用CSS让图片的高度根据宽度调整

当PHP中的宽度大于高度时自动旋转图像