PHP排序工作日和月年通过阵列的客户订单 [英] PHP sort weekday and month-year array by custom order
问题描述
我平日(见下文),我想排序为周一至周二,周三,周四,周五,周六,周日。
I have an array of weekdays (see below) that I would like to sort as "Mon-Tue-Wed-Thu-Fri-Sat-Sun".
"Sun"=>59
"Sat"=>41
"Fri"=>21
"Thu"=>11
"Wed"=>14
"Tue"=>19
"Mon"=>31
我尝试以下code,但它似乎没有正常工作,其结果是有序阵列上方粘贴的,即不是在我想它是命令。
I tried the following code but it doesn't seem to work correctly, the result being the ordered array pasted above, i.e. not in the order I would like it to be.
function orderbyweekday($a, $b) {
if (strcmp($a, "Mon") == 0)
$a = 0;
else if (strcmp($a, "Tue") == 0)
$a = 1;
else if (strcmp($a, "Wed") == 0)
$a = 2;
else if (strcmp($a, "Thu") == 0)
$a = 3;
else if (strcmp($a, "Fri") == 0)
$a = 4;
else if (strcmp($a, "Sat") == 0)
$a = 5;
else if (strcmp($a, "Sun") == 0)
$a = 6;
if (strcmp($b, "Mon") == 0)
$b = 0;
else if (strcmp($b, "Tue") == 0)
$b = 1;
else if (strcmp($b, "Wed") == 0)
$b = 2;
else if (strcmp($b, "Thu") == 0)
$b = 3;
else if (strcmp($b, "Fri") == 0)
$b = 4;
else if (strcmp($b, "Sat") == 0)
$b = 5;
else if (strcmp($b, "Sun") == 0)
$b = 6;
// if same day, return 0
if ($a == $b) {
return 0;
}
return ($a > $b) ? -1 : 1;
}
uksort($movies_per_day, "orderbyweekday");
我还要做类似的事情用一个月的年阵列(例如2010年6月=> 10,2009年5月=> 111等),但一旦我得到这个权利应该是更容易。
I would also like to do a similar thing with an array of month-years (e.g. "June 2010"=>10, "May 2009"=>111, etc.), but once I get this right it should be easier.
非常感谢。
推荐答案
您可以试试这个。
function weekdaySort($a, $b){
$weekdays = array("Mon", "Tue","Wed","Thu","Fri", "Sat", "Sun");
return array_search($a, $weekdays) - array_search($b, $weekdays);
}
uksort($movies_per_day, "weekdaySort");
或者如果你正在使用PHP 5.3或以上,你可以使用一个封闭;
or if you are using php 5.3 or above you can use a closure;
$weekdays = array("Mon", "Tue","Wed","Thu","Fri", "Sat", "Sun");
uksort($movies_per_day, function($a, $b) use ($weekdays) {return array_search($a, $weekdays) - array_search($b, $weekdays);});
这将避免重现 $平日
阵列,每个迭代。
This will avoid recreating the $weekdays
array with each iteration.
这篇关于PHP排序工作日和月年通过阵列的客户订单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!