Search code examples
phparraysarray-multisort

php array multisort didn't return correct results when key has combination of integers and strings


I want to sort an array by ascending order of keys and descending order of values

below is my array before sorting

[undefined] => 166
[template] => 2
[indesign] => 1
[product] => 1
[2] => 3
[4] => 3
[66] => 2
[34] => 1
[2222] => 1

I used below code for sorting

 array_multisort(array_values($data), SORT_DESC, array_keys($data), SORT_ASC, $data);

here the sorted output

   [undefined] => 166
    [0] => 3
    [1] => 3
    [template] => 2
    [2] => 2
    [indesign] => 1
    [product] => 1
    [3] => 1
    [4] => 1

keys which has integers has changed, How can I overcome this?


Solution

  • Code:

    $keys = array_keys($array);
    $values = array_values($array);
    
    array_multisort($values, SORT_DESC, $keys, SORT_ASC | SORT_NATURAL);
    
    $result = array_combine($keys, $values);
    

    Output:

    Array
    (
        [undefined] => 166
        [2] => 3
        [4] => 3
        [66] => 2
        [template] => 2
        [34] => 1
        [2222] => 1
        [indesign] => 1
        [product] => 1
    )