简体   繁体   English

如何按降序对数组的值进行排序

[英]how to sort the valuesof an array in descending order

var_export($array) of an array gives me this:数组的var_export($array)给了我这个:

array 
    ( 

     0 => array ( 'id_20200514222532' => '4', ), 
     1 => array ( 'id_20200521123813' => '5', ), 
     2 => array ( 'id_20200521125410' => '8', ), 
     3 => array ( 'id_20200523003107' => '3', ), 
     4 => array ( 'id_20200523214047' => '2', ), 

    )

It should be sorted in descending order based on the numbers, so first 8 , second 5 and so on...它应该根据数字按降序排序,所以第一个8 ,第二个5等等......

You can use usort() for this, a sorter function that accepts a callback for comparing two values您可以为此使用usort() ,这是一个排序器 function,它接受回调以比较两个值

usort($array, function ($a, $b) {
    return reset($b) - reset($a);
});

That callback function we gave usort() will get two "random" items of the array.我们给usort()的回调 function 将获得数组的两个“随机”项。 I used reset($a) and reset($b) to get the first values out of the child arrays, then I compared them with a simple subtraction.我使用reset($a)reset($b)从子 arrays 中获取第一个值,然后将它们与简单的减法进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM