下面一起来了解下保持数组$array键值由大到小排序,相信大家看完肯定会受益匪浅,文字在精不在多,希望保持数组$array键值由大到小排序这篇短内容是你想要的。
需求:要求保持数组$array键值由大到小,并且其中相同键值的键名要从小到大排序
实现代码如下:
<?
header("Content-type: text/html; charset=UTF-8");
echo '需求:要求保持数组$array键值由大到小,并且其中相同键值的键名要从小到大排序';
echo '<pre />';
$array = array(
'5' => 100,
'3' => 80,
'1' => 80,
'4' => 60,
'0' => 60,
'2' => 40
);
$kArr=array();
$vArr=array();
$newkArr=array();
foreach($array as $key=>$value){
$kArr[]=$key;
$vArr[]=$value;
}
$kStr=implode(",",$kArr);
$repeatArr=array();
foreach($array as $k=>$v){
$arrn[$v][]=$k;
}
foreach($arrn as $k=>$v){
if(count($v)>1){
//echo $k.'重复下标为';
$aa='';
foreach($v as $vv){
$aa .= $vv.',';
}
$bb=substr($aa, 0, -1);
$bbarr=explode(',',$bb);
sort($bbarr);
$bbstr=implode(',',$bbarr);
$repeatArr[$bb] = $bbstr;
}
}
foreach($repeatArr as $key=>$value){
$kStr=str_replace($key,$value,$kStr);
}
$newkArr=explode(',',$kStr);
echo '<hr />';
$c=array_combine($newkArr,$vArr);
print_r($c);
今天有个高手帮写了个方法:一起膜拜下
function sysSortArray($ArrayData,$KeyName1,$SortOrder1 = "SORT_ASC",$SortType1 = "SORT_REGULAR"){
if(!is_array($ArrayData)){
return $ArrayData;
}
// Get args number.
$ArgCount = func_num_args();
// Get keys to sort by and put them to SortRule array.
for($I = 1;$I < $ArgCount;$I ++){
$Arg = func_get_arg($I);
if(!eregi("SORT",$Arg)){
$KeyNameList[] = $Arg;
$SortRule[] = '$'.$Arg;
}
else{
$SortRule[] = $Arg;
}
}
// Get the values according to the keys and put them to array.
foreach($ArrayData AS $Key => $Info){
foreach($KeyNameList AS $KeyName){
${$KeyName}[$Key] = $Info[$KeyName];
}
}
// Create the eval string and eval it.
$EvalString = 'array_multisort('.join(",",$SortRule).',$ArrayData);';
eval ($EvalString);
return $ArrayData;
}
$data = array('0'=>60,'1'=>80,'2'=>40,'3'=>80,'4'=>60,'5'=>100);
$sorts=array();
foreach($data as $k => $val){
$sorts[$k]['k']=$k;
$sorts[$k]['val']=$val;
}
$rs=sysSortArray($sorts,'val',"SORT_DESC","k","SORT_DESC");
print_r($rs);die;
看完保持数组$array键值由大到小排序这篇文章后,很多读者朋友肯定会想要了解更多的相关内容,如需获取更多的行业信息,可以关注我们的行业资讯栏目。