PHP array sort using inner val

前端 未结 3 413
暖寄归人
暖寄归人 2021-01-04 23:12
Array
(
[1] => Array
    (
        [id] => 1
        [sort] => 1
    )

[3] => Array
    (
        [id] => 3
        [sort] => 3
    )

[2] => A         


        
相关标签:
3条回答
  • 2021-01-04 23:32

    Something like this:

    usort($array, function (array $a, array $b) { return $a["sort"] - $b["sort"]; });
    
    0 讨论(0)
  • 2021-01-04 23:33

    Something like this:

    uasort($array, 'compfunc');
    
    function compfunc($a, $b)
    {
        return $a['sort'] - $b['sort'];
    }
    
    0 讨论(0)
  • 2021-01-04 23:49

    You can use usort with this comparison function:

    function cmpBySort($a, $b) {
        return $a['sort'] - $b['sort'];
    }
    usort($arr, 'cmpBySort');
    

    Or you use array_multisort with an additional array of key values for the sort order:

    $keys = array_map(function($val) { return $val['sort']; }, $arr);
    array_multisort($keys, $arr);
    

    Here array_map with the anonymous function is used to build an array of the sort values that is used to sort the array values itself. The advantage of this is that there is np comparison function that needs to be called for each pair of values.

    0 讨论(0)
提交回复
热议问题