How do I sort a PHP array by an element nested inside?

前端 未结 8 2171
长情又很酷
长情又很酷 2020-12-05 23:00

I have an array like the following:

Array
(
    [0] => Array
        (
            \'name\' => \"Friday\"
            \'weight\' => 6
        )
    [1] => Array
          


        
相关标签:
8条回答
  • 2020-12-05 23:22

    You can use usort as:

    function cmp($a, $b) {
       return $a['weight'] - $b['weight'];
    }
    
    usort($arr,"cmp");
    
    0 讨论(0)
  • 2020-12-05 23:23

    NOTE, if the element you are sorting on is a float like .0534 and .0353 (like for a percentage), then you have to multiply both by 1000. not sure why frankly... it appears that usort seems to compare the integer values.

    took me awhile to figure that one out...

    and 2 tips that may not be immediately obvious:

    1. if your arrays are objects, you can use return $a->weight - $b->weight of course
    2. if you return $b->weight - $a->weight, it will sort desending.
    0 讨论(0)
提交回复
热议问题