首页  >  文章  >  后端开发  >  共享一个PHP对二维数组的某个字段进展升降排序类

共享一个PHP对二维数组的某个字段进展升降排序类

WBOY
WBOY原创
2016-06-13 13:19:42766浏览

共享一个PHP对二维数组的某个字段进行升降排序类

<?php
/**
 * @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;
    }
}
?>
?

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn