admin
管理员
管理员
  • UID1
  • 粉丝2
  • 关注2
  • 发帖数339
  • 社区居民
  • 忠实会员
  • 原创写手
阅读:3960回复:0

PHP中按二维数组的某个字段进行排序类

楼主#
更多 发布于:2014-04-08 11:46
分享到:
<?php  
    /** 
     * @from author paul <199921128@qq.com>
     * @desc 按二维数组的某一个字段进行升降排序 
     * @data 
     *      $testData = array( 
                array('newPrice'=>9), 
                array('newPrice'=>21), 
                array('newPrice'=>15), 
                array('newPrice'=>13), 
                array('newPrice'=>12) 
            ); 
     */ 
    class sortClass{  
        //升序  
        function sortArrayAsc($preData,$sortType='newPrice'){  
            $sortData = array();  
            foreach ($preData as $key_i => $value_i){  
                $price_i = $value_i[$sortType];  
                $min_key = '';  
                $sort_total = count($sortData);  
                foreach ($sortData as $key_j => $value_j){  
                    if($price_i<$value_j[$sortType]){  
                        $min_key = $key_j+1;  
                        break;  
                    }  
                }  
                if(empty($min_key)){
                    array_push($sortData, $value_i);   
                }else {  
                    $sortData1 = array_slice($sortData, 0,$min_key-1);   
                    array_push($sortData1, $value_i);  
                    if(($min_key-1)<$sort_total){  
                        $sortData2 = array_slice($sortData, $min_key-1);   
                        foreach ($sortData2 as $value){  
                            array_push($sortData1, $value);  
                        }  
                    }  
                    $sortData = $sortData1;  
                }  
            }  
            return $sortData;  
        }  
        //降序  
        function sortArrayDesc($preData,$sortType='newPrice'){  
            $sortData = array();  
            foreach ($preData as $key_i => $value_i){  
                $price_i = $value_i[$sortType];  
                $min_key = '';  
                $sort_total = count($sortData);  
                foreach ($sortData as $key_j => $value_j){  
                    if($price_i>$value_j[$sortType]){  
                        $min_key = $key_j+1;  
                        break;  
                    }  
                }  
                if(empty($min_key)){  
                    array_push($sortData, $value_i);   
                }else {  
                    $sortData1 = array_slice($sortData, 0,$min_key-1);   
                    array_push($sortData1, $value_i);  
                    if(($min_key-1)<$sort_total){  
                        $sortData2 = array_slice($sortData, $min_key-1);   
                        foreach ($sortData2 as $value){  
                            array_push($sortData1, $value);  
                        }  
                    }  
                    $sortData = $sortData1;  
                }  
            }  
            return $sortData;  
        }  
    }  
    ?>
游客

返回顶部