How to sort a multidimensional array by a certain key?

前端 未结 5 1592
误落风尘
误落风尘 2020-11-27 08:15

This should be really simple, but what is the way to go on this. I want to sort an multidimensional array by a key, like this:

Array (
[0] => Array
    (         


        
相关标签:
5条回答
  • 2020-11-27 08:41

    Try this

    function cmp_by_status($a, $b)
    {
        if ($a['status'] == $b['status']) {
            return 0;
        }
        return ($a['status'] < $b['status') ? -1 : 1;
    }
    
    usort($data_array, "cmp_by_status");
    
    0 讨论(0)
  • 2020-11-27 08:45

    usort function is what you're looking for:

    <?php
        function cmp($a, $b) {
            return $b["status"] - $a["status"];
        }
    
        $sorted = usort($your_array, "cmp");
        var_dump($sorted);
    ?>
    
    0 讨论(0)
  • 2020-11-27 08:46

    Try this : Using array_multisort

    $sort = array();
    foreach($your_array as $k=>$v) {
        $sort['status'][$k] = $v['status'];
    }
    
    array_multisort($sort['status'], SORT_DESC, $your_array);
    
    
    echo "<pre>";
    print_r($your_array);
    

    Ref: http://php.net/manual/en/function.array-multisort.php

    0 讨论(0)
  • 2020-11-27 08:57
    //define a comparison function
    function cmp($a, $b) {
        if ($a['status'] == $b['status']) {
            return 0;
        }
        return ($a['status'] < $b['status']) ? -1 : 1;
    }
    
    usort($array, "cmp");
    

    That should do what you want, you can alter the comparison function to sort on whatever key you want.

    0 讨论(0)
  • 2020-11-27 09:01

    I have added this answer at Sort multi-dimensional array by specific key sort the array specific key to sorting array value.

    function sortBy($field, &$array, $direction = 'asc')
    {
        usort($array, create_function('$a, $b', '
            $a = $a["' . $field . '"];
            $b = $b["' . $field . '"];
    
            if ($a == $b)
            {
                return 0;
            }
    
            return ($a ' . ($direction == 'desc' ? '>' : '<') .' $b) ? -1 : 1;
        '));
    
        return true;
    }
    

    Call this function by specific array key

    sortBy('status',   $array);
    
    0 讨论(0)
提交回复
热议问题