php 在类中使用usort 对二维数组排序
一、普通php文件中二维数组排序后显示
一维数组排序,PHP自身就提供了很多函数,比如sort,rsort,ksort…这些查手册文档都有,
这里我们要说的是对二维数组的排序,也就是自定义排序usort
//自定义排序函数
function fruitPriceDesc( $a, $b ){
$returnFlag = 0;
if ($a['price'] == $b['price']){
$returnFlag = 0;
}else{
$returnFlag = $a['price'] > $b['price'] ? 1:0;
}
}
//调用自定义排序 usort( 要排序的数组, 自定义比较大小的函数名 )
usort($fruitArray,"fruitPriceDesc");
二、在类文件中对二维数组自定义排序
在类中调用的时候,函数名不能直接写,要写一个数组:
usort( $needFormatData, array( $this, “newsListDateDesc”) );
/**
* @param $a
* @param $b
* TODO 使用usort排序
*/
public function getRecommendationList($params = array())
{
$mustRecommendationList = $this->getMustRecommendationList();
usort($needFormatData, array($this, "newsListDateDesc") );
return $needFormatData;
}
/**
* @param $a
* @param $b
* TODO 自定义排序函数
*/
protected function newsListDateDesc( $a, $b ){
$returnFlag = 0;
if ($a['ndate'] == $b['ndate']){
$returnFlag = 0;
}else{
$returnFlag = $a['ndate'] < $b['ndate'] ? 1:0;
}
}