2 回答
TA贡献1836条经验 获得超13个赞
尝试这个
<?php
$time= ['10' => '06:30pm','20' => '04:00pm', '30' => '05:15am'];
$temp_time=array();
foreach ($time as $key => $value) {
if(sizeof(explode("pm", $value))>1){
$data=explode(":", $value);
$data[0]=(int)$data[0]+12;
$value=$data[0].':'.$data[1];
}else{
$data=explode(":", $value);
if($data[0]=='12'){
$value='00:'.$data[1];
}else{
$value=$data[0].':'.$data[1];
}
}
$temp_time+=[$key => $value];
}
asort($temp_time);
$new_time=array();
foreach ($temp_time as $key => $value) {
$new_time+=[$key => $time[$key]];
}
print_r($new_time);
输出:
Array ( [30] => 05:15am [20] => 04:00pm [10] => 06:30pm )
TA贡献1864条经验 获得超6个赞
这是解决方案:
$source_array = array(10 => '06:30pm', 20 => '04:00pm', 30 => '05:15pm', 40 => '04:00am');
function arr_swap_elements(&$arr, $a_index, $b_index) {
$tmp = $arr[$a_index];
$arr[$a_index] = $arr[$b_index];
$arr[$b_index] = $tmp;
return;
}
function arr_sort_by_time(&$source_array, $start_index = 0, $arr_keys = null, $arr_len = null) {
if (is_null($arr_keys)) {
$arr_keys = array_keys($source_array);
}
if (is_null($arr_len)) {
$arr_len = count($source_array);
}
for ($i = $start_index; $i < $arr_len; $i++) {
if ($i > 0) {
if (strtotime($source_array[$arr_keys[$i]]) > strtotime($source_array[$arr_keys[$i - 1]])) {
$was_swapped = true;
arr_swap_elements($source_array, $arr_keys[$i], $arr_keys[$i - 1]);
}
}
}
if ($start_index + 1 < $arr_len) {
arr_sort_by_time($source_array, $start_index + 1, $arr_keys, $arr_len);
}
}
arr_sort_by_time($source_array);
var_dump($source_array);
- 2 回答
- 0 关注
- 120 浏览
添加回答
举报