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

前端 未结 8 2185
长情又很酷
长情又很酷 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:09

    Can be done using an anonymous function.

    Also if your 'weight' is a string use one of the other returns (see the commented out lines):

     array (
            'name'   => 'Friday',
            'weight' => 6,
        ),
        1 => array (
            'name'   => 'Monday',
            'weight' => 2,
        ),
    );
    
    // sort by 'weight'
    usort($arr, function($a, $b) { // anonymous function
        // compare numbers only
        return $a['weight'] - $b['weight'];
    
        // compare numbers or strings
        //return strcmp($a['weight'], $b['weight']);
    
        // compare numbers or strings non-case-sensitive
        //return strcmp(strtoupper($a['weight']), strtoupper($b['weight']));
    });
    
    var_export($arr);
    
    /*
    array (
        0 => array (
            'name'   => 'Monday',
            'weight' => 2,
        ),
        1 => array (
            'name'   => 'Friday',
            'weight' => 6,
        ),
    )
    */
    

提交回复
热议问题