A-A+

PHP 根据某个字段对数组这个数组排序

2014年11月26日 10:27 汪洋大海 暂无评论 阅读 198 views 次

阿虎同学,要求将一个数组根据元素出现的次数来行进排列:
要求输出结果如下:
3出现5次
4出现2次
1出现2次

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
function getNumberOfCalculations($array,$orderby="desc"){
 
        $newArr =array();
        $count = 0;
 
        foreach ($array as $key => $value) {
 
            foreach ($array as $k => $v) {
                if($value == $v){
                    $count++;
                }
            }
 
            if($count >0){
                $new['value'] = $value;
                $new['count'] = $count;
                array_push($newArr, $new) ;
            }
            unset($count);
        }
 
        $countArr  = array();
        $countArr2  = array();
        foreach ($newArr as $key1 => $value1) {
            $countArr[$value1['value']] = $value1['count'];
        }
 
        foreach ($countArr as $key2 => $value2) {
            $countA['value']=$key2;
            $countA['count']=$value2;
            $countArr2[] = $countA;
        }
 
        foreach ($countArr2 as $key3=>$value3){
            $value4[$key3] = $value3['value'];
            $count4[$key3] = $value3['count'];
        }
 
        if($orderby != 'desc'){
            array_multisort($count4,SORT_NUMERIC,SORT_ASC,$value4,SORT_STRING,SORT_ASC,$countArr2);
        }else{
            array_multisort($count4,SORT_NUMERIC,SORT_DESC,$value4,SORT_STRING,SORT_DESC,$countArr2);
        }
 
        return $countArr2;
}
 
$arr=array(1,2,3,4,23,44,0,45,3,0,3,1,2,3,4,23,44,0,45,3,0,3,45,9,123,6768,1232,99,9,99,111111,9999,99);
$array = getNumberOfCalculations($arr,"desc");
 
foreach ($array as $key => $value) {
    echo $value['value'] . "出现了:". $value['count'] ." 次</br>";
}

执行之后如下图:


php 根据某个字段对二维数组这个数组排序

http://www.pooy.net/php-getnumberofcalculations.html 文章来路。

标签:

评论已关闭!