猿问

在保持名称的同时按时间对数组进行排序

我有以下数组: Array ( [10] => 06:30pm [20] => 04:00pm [30] => 05:15pm )

[]中的数字是id,后面的值是时间。我需要按时间对这个数组进行排序,同时像这样维护 id

数组([20] => 下午 4 点 00 分 [30] => 下午 5 点 15 分 [10] => 下午 6 点 30 分)

另请注意,时间也可以是上午或下午。

然后我需要将 [] 中的 id 提取为逗号分隔值。

谁能帮忙?


慕婉清6462132
浏览 121回答 2
2回答

开心每一天1111

尝试这个<?php$time= ['10' => '06:30pm','20' => '04:00pm', '30' => '05:15am'];$temp_time=array();foreach ($time as $key => $value) {&nbsp; &nbsp; if(sizeof(explode("pm", $value))>1){&nbsp; &nbsp; &nbsp; &nbsp; $data=explode(":", $value);&nbsp; &nbsp; &nbsp; &nbsp; $data[0]=(int)$data[0]+12;&nbsp; &nbsp; &nbsp; &nbsp; $value=$data[0].':'.$data[1];&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; $data=explode(":", $value);&nbsp; &nbsp; &nbsp; &nbsp; if($data[0]=='12'){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $value='00:'.$data[1];&nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $value=$data[0].':'.$data[1];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; $temp_time+=[$key => $value];}asort($temp_time);$new_time=array();foreach ($temp_time as $key => $value) {&nbsp; &nbsp; $new_time+=[$key => $time[$key]];}print_r($new_time);输出:Array ( [30] => 05:15am [20] => 04:00pm [10] => 06:30pm )

慕尼黑的夜晚无繁华

这是解决方案:$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);
随时随地看视频慕课网APP
我要回答