php - 当键具有整数和字符串的组合时,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
具有整数的键已更改,我该如何克服?
解决方案
代码:
$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
)
推荐阅读
- php - 将 orWhere() 附加到动态子查询
- javascript - javascript 尝试导入不存在的文件
- file - 使用批处理添加到子文件夹的文件名中
- google-bigquery - 是否可以检索完整的查询历史记录并关联其在 google bigquery 中的成本?
- xcode - 在隐式展开可选值 1 时意外发现 nil
- oauth - 如果 oauth 是无状态的,谷歌如何销毁 oauth 令牌?
- python - 在 ElementTree 中获取整个父标签的文本
- react-native - 在 React Native 的 ScrollView 中滚动时动画导航标题不透明度?
- scala - 无法使用 Spark Submit 找到 akka 配置
- r - 我如何按特定日期分组,然后使用 R 找到列的总和?