PHP 按最大宽度和宽度大于高度的位置对图片进行排序
PHP Sort pictures by biggest width and where width is bigger than height
我有一个这样的数组:
array(
0 => array(
width => "213",
height => "50"
),
1 => array(
width => "120",
height => "204"
)
) etc...
现在我想按宽度值最大且宽度大于高度的图片对这个数组进行排序。
我的尝试是,使用 usort()
:
usort($results['bossresponse']['images']['results'], function($a, $b) {
return $b['width'] - $a['width'];
});
但它只是根据宽度对图片进行排序,如果图片的宽度大于高度则不会。 usort 可以吗?
试试这个:
usort($results['bossresponse']['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;
});
我有一个这样的数组:
array(
0 => array(
width => "213",
height => "50"
),
1 => array(
width => "120",
height => "204"
)
) etc...
现在我想按宽度值最大且宽度大于高度的图片对这个数组进行排序。
我的尝试是,使用 usort()
:
usort($results['bossresponse']['images']['results'], function($a, $b) {
return $b['width'] - $a['width'];
});
但它只是根据宽度对图片进行排序,如果图片的宽度大于高度则不会。 usort 可以吗?
试试这个:
usort($results['bossresponse']['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;
});