这是我要按工作日(周一到周日)排序的数组 我已经检查了类似的问题,但没有一个能帮助解决这个问题。
$data =
array (
0 =>
array (
'mid' => 19,
'centerid' => 1,
'sid' => 13,
'weekday' => 'tuesday',
'break' => 1,
),
1 =>
array (
'mid' => 14,
'centerid' => 1,
'sid' => 13,
'weekday' => 'wednesday',
'break' => 1,
),
2 =>
array (
'mid' => 12,
'centerid' => 1,
'sid' => 13,
'weekday' => 'monday',
'break' => 1,
),
3 =>
array (
'mid' => 17,
'centerid' => 1,
'sid' => 13,
'weekday' => 'monday',
'break' => 0,
),
);
usort($data, array($this,'cmp'));
我已尝试过对它进行排序
function cmp($a, $b){
$a = strtotime($a['weekday']);
$b = strtotime($b['weekday']);
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
但它不起作用而且是无序的。有人可以帮我吗?
答案 0 :(得分:1)
试试这个cmp
功能
function cmp($a, $b){
$a = date('N', strtotime($a['weekday']));
$b = date('N', strtotime($b['weekday']));
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
答案 1 :(得分:1)
您可以编写将日名称映射到数字的函数,并在cmp
函数中使用它:
<?php
$data =
array (
0 =>
array (
'mid' => 19,
'centerid' => 1,
'sid' => 13,
'weekday' => 'tuesday',
'break' => 1,
),
1 =>
array (
'mid' => 14,
'centerid' => 1,
'sid' => 13,
'weekday' => 'wednesday',
'break' => 1,
),
2 =>
array (
'mid' => 12,
'centerid' => 1,
'sid' => 13,
'weekday' => 'monday',
'break' => 1,
),
3 =>
array (
'mid' => 17,
'centerid' => 1,
'sid' => 13,
'weekday' => 'monday',
'break' => 0,
),
);
usort($data, array($this,'cmp'));
function getNumberOfDayByDayName($dayName)
{
$map = array(
'monday'=>1,
'tuesday'=>2,
'wednesday'=>3,
'thursday'=>4,
'friday'=>5,
'saturday'=>6,
'sunday'=>7,
);
return $map[$dayName];
}
function cmp($a, $b){
$a = getNumberOfDayByDayName($a['weekday']);
$b = getNumberOfDayByDayName($b['weekday']);
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
echo '<pre>';
print_r($data);
echo '</pre>';
结果是:
Array
(
[0] => Array
(
[mid] => 17
[centerid] => 1
[sid] => 13
[weekday] => monday
[break] => 0
)
[1] => Array
(
[mid] => 12
[centerid] => 1
[sid] => 13
[weekday] => monday
[break] => 1
)
[2] => Array
(
[mid] => 19
[centerid] => 1
[sid] => 13
[weekday] => tuesday
[break] => 1
)
[3] => Array
(
[mid] => 14
[centerid] => 1
[sid] => 13
[weekday] => wednesday
[break] => 1
)
)
工作示例:CLICK