php 当键具有整数和字符串的组合时,数组多重排序没有 return 正确的结果
php array multisort didn't return correct results when key has combination of integers and strings
我想按键的升序和值的降序对数组进行排序
下面是我排序前的数组
[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
具有整数的键已更改,我该如何克服这个问题?
代码:
$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
)
我想按键的升序和值的降序对数组进行排序
下面是我排序前的数组
[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
具有整数的键已更改,我该如何克服这个问题?
代码:
$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
)