1

I have the following array: Array ( [10] => 06:30pm [20] => 04:00pm [30] => 05:15pm )

The number in [] is the id and follow by the value is time. I need to sort this array by time while maintaining the id like this

Array ( [20] => 04:00pm [30] => 05:15pm [10] => 06:30pm )

Please also note that the time can be in AM or PM also.

I would then need to extract the id in the [] as comma separated value.

Can anyone help?

2 Answers 2

1

try this

<?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);

output:

Array ( [30] => 05:15am [20] => 04:00pm [10] => 06:30pm )
Sign up to request clarification or add additional context in comments.

Comments

0

Here is the solution:

$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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.