How do I sort a multi-dimensional array by value?

后端 未结 3 1251
难免孤独
难免孤独 2020-12-07 01:52

I have an array as following and I want to order that array by the value of the key \"attack\". First keys of the arrays (15, 13, 18) are ID of some certain ite

相关标签:
3条回答
  • 2020-12-07 02:34

    Simply use array_multisort

    foreach ($data as $key => $row) {
        $attack[$key]  = $row['attack'];
    }
    
    // Sort the data with attack descending
    array_multisort($attack, SORT_DESC, $data);
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-07 02:37

    Use uasort():

    This function sorts an array such that array indices maintain their correlation with the array elements they are associated with, using a user-defined comparison function.

    This is used mainly when sorting associative arrays where the actual element order is significant.

    Example:

    function cmp($a, $b) {
        if ($a['attack'] == $b['attack']) {
            return 0;
        }
        return ($a['attack'] < $b['attack']) ? -1 : 1;
    } 
    
    uasort($data, 'cmp');
    

    If the values are always strings, you can also use strcmp() in the cmp() function:

    function cmp($a, $b) {
        return strcmp($a['attack'], $b['attack']);
    } 
    

    Update:

    To sort in descending order you just have to change the return values:

    return ($a['attack'] < $b['attack']) ? 1 : -1;
    //                                     ^----^
    

    or to pick up @salathe's proposal:

    return $b['attack'] - $a['attack'];
    
    0 讨论(0)
  • 2020-12-07 02:37
    $result = [];
    foreach ($data as $key => $value) {
        $result[$key] = $value;
        asort($result[$key]);
    }
    print_r($result);
    

    Hope this helps !!!

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