我有一个像
这样的数组Array
(
[0] => Array
(
[id] => 21
[time] => FOUR_DAY
[zones] => 25
)
[1] => Array
(
[id] => 20
[time] => THREE_DAY
[zones] => 2
)
[2] => Array
(
[id] => 22
[time] => ONE_DAY
[zones] => 2
)
[3] => Array
(
[id] => 24
[time] => ONE_DAY
[zones] => 2
)
)
我需要的是
1-按'time'字段排序,使用
$time = array('ONE_DAY','TWO_DAYS','THREE_DAYS','FOUR_DAYS','FIVE_DAYS');
2-然后将上述结果按"zone"按ASC顺序排序。
预期输出:Array
(
[0] => Array
(
[id] => 22
[time] => ONE_DAY
[zones] => 2
)
[1] => Array
(
[id] => 24
[time] => ONE_DAY
[zones] => 2
)
[2] => Array
(
[id] => 20
[time] => THREE_DAY
[zones] => 2
)
[3] => Array
(
[id] => 21
[time] => FOUR_DAY
[zones] => 25
)
)
请给我一个好的选择。我已经尝试了usort
的"时间"字段和multi_sort
函数。但还是原地不动。提前感谢!!
您应该使用usort
来完成这项工作。
试试这样写:
$sorted = usort($notSorted, function($a, $b) {
//array of times to compare
$time = array('ONE_DAY','TWO_DAYS','THREE_DAYS','FOUR_DAYS','FIVE_DAYS');
//check index of time in $times array
$aKey = array_search($a['time'], $times);
$bKey = array_search($b['time'], $times);
//if the same - then compare by zones;
if($aKey == $bkey) {
return $a['zones'] - $b['zones'];
//else compare by time's indexes
} else {
return ($aKey-$bKey);
}
});
Not testing by表示这个想法。
查看PHP手册中usort
的详细信息
$order = array("ONE_DAY","TWO_DAY","THREE_DAY","FOUR_DAY");
$test[4] =array("id"=>21,"time"=>"FOUR_DAY","zones"=>25);
$test[1] =array("id"=>20,"time"=>"THREE_DAY","zones"=> 2);
$test[2] =array("id"=>22,"time"=>"ONE_DAY","zones"=>2);
$test[3] =array("id"=>24,"time"=>"ONE_DAY","zones"=>2);
$newarray=array();
foreach($test as $kk=>$t){
$newarray[$kk]=$t["time"];
}
$final=array();
foreach($order as $key=>$f){
$mykey=array_keys($newarray,$f);
if(is_array($mykey)){
foreach($mykey as $key){
$final[]=$test[$key];
}
}
}
echo "<pre>";
print_r($final);
echo "</pre>";
谢谢大家!我终于找到了解决问题的办法。
由于$time是预定义值,所以
代替
使用array_multisort代替 ussort
希望这对某些人有所帮助!!
谢谢! !