dsadasd12132
dsadasd12132
2019-01-06 18:54
浏览 49
已采纳

当key具有整数和字符串的组合时,php array multisort没有返回正确的结果

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongshi4773
    dongshi4773 2019-01-06 19:27
    已采纳

    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
    )
    
    点赞 评论

相关推荐