1

I have an array which generated using PHP as below:

[
    ['user' => 'test 1', 'esttime' => '5 mins', 'destination' => 'testing location svvfefhsrdfd'],
    ['user' => 'test 2', 'esttime' => '5 mins', 'destination' => 'testing location fsdfdsv'],
    ['user' => 'test 5', 'esttime' => '8 mins', 'destination' => 'testing location scvvfe'],
    ['user' => 'test 3', 'esttime' => '5 mins', 'destination' => 'testing location sfds'],
    ['user' => 'test 4', 'esttime' => '8 mins', 'destination' => 'testing location gfsdarr'],
    ['user' => 'test 6', 'esttime' => '10 mins', 'destination' => 'testing location dgfd']
]

The array have keys user,estimate time and destination and related values, I need to sort this array using esttime column value.

0

2 Answers 2

2

You could use custom sorting usort() in this case, then just use strtotime() for that relative time:

usort($array, function($a, $b){
    $time_a = strtotime($a['esttime']);
    $time_b = strtotime($b['esttime']);

    return $time_a - $time_b;
});

echo '<pre>';
print_r($array);

Sample Out

Sign up to request clarification or add additional context in comments.

4 Comments

I like this idea, that's a smart way to do it. I never would have even thought about a strtotime()...well obviously by my answer...
@Rasclatt that's a standard way, nothing special here.
@Rasclatt i maybe a little bit better handling the time, since we don't know maybe the OP might get an obscure case of 5mins 3hours etc. might be better to handle it in its time context
Well, I learned something anyway (even if it is nothing special to other folks).
1

One way to do it is to generate a new array:

foreach($array as $row) {
        $new[str_replace(" ","_",$row['esttime'])][] = $row;
    }

print_r($new) Should look like this after:

Array (
        [5_mins][0] => Array ([user] => test 1 [esttime] => 5 mins [destination] => testing location svvfefhsrdfd)
        [5_mins][1] => Array ( [user] => test 2 [esttime] => 5 mins [destination] => testing location fsdfdsv)
        [5_mins][2] => Array ( [user] => test 3 [esttime] => 5 mins [destination] => testing location sfds)
        [8_mins][0] => Array ( [user] => test 5 [esttime] => 8 mins [destination] => testing location scvvfe )
        [8_mins][1] => Array ( [user] => test 4 [esttime] => 8 mins [destination] => testing location gfsdarr )
        [10_mins][0] => Array ( [user] => test 6 [esttime] => 10 mins [destination] => testing location dgfd )
      )

2 Comments

usort works on O(nlogn), while this way works on O(n). Faster algorithm.
@CertaiN this is like grouping rather than sorting. The OP's sample data is just an example, I don't think this can actually sort something more complex. for example try on this data 6 mins, 5 mins, 10 mins (note that the OP's data is nearly sorted, so this works on that data).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.