phparrayssortingkeynatural-sort

Naturally sort an associative subarray by its keys in a descending direction


I'm trying to sort an array by the value of a sub-key in DESC order but I'm stuck. I've could make it with ksort but it was in ascending order.

Here's my array:

$array_by_lang = array(
    [no] => array(
        [3-1] => array(//some informations),
        [3-10] => array(//informations),
        [3-7] => array(//informations),
        [5-1] => array(//informations)
    )
)

What I want to obtain is something like:

$array_by_lang = array(
    [no] => array(
        [5-1] => array(//informations),
        [3-10] => array(//some informations),
        [3-7] => array(//informations),
        [3-1] => array(//informations)
    )
)

Solution

  • I think, you need "reversing natural sort by key". Just with array_multisort and array_reverse (see also natsort):

        $array_by_lang = array(
            'no' => array(
                '3-1'  => array('info_1'),
                '3-10' => array('info_2'),
                '3-7'  => array('info_3'),
                '5-1'  => array('info_4'),
            )
        );
    
    
        array_multisort(array_keys($array_by_lang['no']),SORT_NATURAL, $array_by_lang['no']);
        $array_by_lang['no'] = array_reverse($array_by_lang['no']); // reverse natural order - "DESC"
        var_dump($array_by_lang);
    

    Output

    array(1) {
      ["no"]=>
        array(4) {
        ["5-1"]=>
          array(1) {
            [0]=>
            string(6) "info_4"
        }
        ["3-10"]=>
          array(1) {
            [0]=>
            string(6) "info_2"
        }
        ["3-7"]=>
          array(1) {
            [0]=>
            string(6) "info_3"
        }
        ["3-1"]=>
          array(1) {
           [0]=>
           string(6) "info_1"
        }
       }
    }