问题描述:

I have an array like this one:

 array(

0 => array(

width => "213",

height => "50"

),

1 => array(

width => "120",

height => "204"

)

) etc...

Now I want to order this array by the pictures with the biggest width worth and where the width is bigger than the height.

My try to do this was that, using usort():

usort($results['bossresponse']['images']['results'], function($a, $b) {

return $b['width'] - $a['width'];

});

But it sort's the pictures just for their width, not if the picture have a bigger width than the height. Is it possible with usort?

网友答案:

Try this:

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;
});
相关阅读:
Top