我有一个类似
的数组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 = array('ONE_DAY','TWO_DAYS','THREE_DAYS','FOUR_DAYS','FIVE_DAYS');
2-然后按照以下区域对上述结果进行排序'按照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
函数。但卡住了。
在此先感谢!!
答案 0 :(得分:0)
您应该使用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);
}
});
未通过测试显示出这个想法。
在PHP手册中查看usort
的详细信息
答案 1 :(得分:0)
$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>";
答案 2 :(得分:0)
全部谢谢!!我终于找到了解决问题的方法 由于 $ time 具有预定义值,因此替换为
$time = array('ONE_DAY','TWO_DAYS','THREE_DAYS','FOUR_DAYS','FIVE_DAYS');
AS
$time = array(1=>'ONE_DAY',2=>'TWO_DAYS',3=>'THREE_DAYS',4=>'FOUR_DAYS',5=>'FIVE_DAYS');
使用 array_multisort 代替 usort
`foreach($myArray as $key=>$response){`enter code here` $sortNumber = array_search($response['time'],$time); $myArray [$key]['numericTimes'] = ($sortNumber)?$sortNumber:"NULL"; $sortByTime[$key] = array_search($response['time'],$time); $sortBtZone[$key] = $response['zones']; }` array_multisort($sortByTime, SORT_ASC, $sortBtZone, SORT_ASC, $myArray);
希望这在某些方面对某人有帮助!!
谢谢!