首页 > 解决方案 > 当键具有整数和字符串的组合时,php数组多重排序没有返回正确的结果

问题描述

我想按键的升序和值的降序对数组进行排序

下面是我排序前的数组

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

我使用下面的代码进行排序

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

这里是排序的输出

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

具有整数的键已更改,我该如何克服?

标签: phparraysarray-multisort

解决方案


代码:

$keys = array_keys($array);
$values = array_values($array);

array_multisort($values, SORT_DESC, $keys, SORT_ASC | SORT_NATURAL);

$result = array_combine($keys, $values);

输出:

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

推荐阅读