作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我不明白为什么 asort 不起作用。任何其他排序都不起作用。 $hs['hs_type'] 是来自 MySQL 查询的值。
$results = $query->result_array();
$hs_types = array();
foreach($results as $hs) {
$hs_types[$hs['hs_type']]++;
}
$projects = array();
foreach($hs_types as $hs) {
array_push($projects, $hs);
}
asort($projects);
排序前数组的 var_dump:数组 (size=15)
* 8 => int 1709
* 13 => int 26
* 7 => int 474
* 14 => int 800
* 11 => int 282
* 6 => int 61
* 5 => int 23
* 15 => int 181
* 3 => int 2
* 19 => int 3
* 9 => int 50
* 1 => int 44
* 2 => int 2
* 4 => int 4
* 18 => int 13
排序后数组的 var_dump:数组 (size=15)
* 8 => int 2
* 12 => int 2
* 9 => int 3
* 13 => int 4
* 14 => int 13
* 6 => int 23
* 1 => int 26
* 11 => int 44
* 10 => int 50
* 5 => int 61
* 7 => int 181
* 4 => int 282
* 2 => int 474
* 3 => int 800
* 0 => int 1709
我想要什么:
* 3 => int 2
* 2 => int 2
* 19 => int 3
* 4 => int 4
* 18 => int 13
* 5 => int 23
* 13 => int 26
* 1 => int 44
* 9 => int 50
* 15 => int 181
* 11 => int 282
* 7 => int 474
* 14 => int 800
* 8 => int 1709
最佳答案
问题是您将所有内容放入精心设置的键控数组中,然后将每个项目插入 $projects 数组(丢失键),然后对 $projects 数组进行排序。
它显示了这个小测试脚本:-
<?php
$hs_types = array(8 => 1709,
13 => 26,
7 => 474,
14 => 800,
11 => 282,
6 => 61,
5 => 23,
15 => 181,
3 => 2,
19 => 3,
9 => 50,
1 => 44,
2 => 2,
4 => 4,
18 => 13);
Echo "\r\nOriginal array\r\n";
print_r($hs_types);
$projects = array();
foreach($hs_types as $hs)
{
array_push($projects, $hs);
}
asort($projects);
Echo "\r\nPushed array sorted\r\n";
print_r($projects);
asort($hs_types);
Echo "\r\nOriginal array sorted\r\n";
print_r($hs_types);
?>
但看起来首先在 SQL 中获取排序列表会更容易。
关于php - 如何在 PHP 中按值对数组进行排序并保留键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21909895/
我是一名优秀的程序员,十分优秀!