Suneth Kalhara
Suneth Kalhara

Reputation: 1208

Sort rows of a 2d array naturally by a column containing numeric and non-numeric characters

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.

Upvotes: 1

Views: 254

Answers (2)

Kevin
Kevin

Reputation: 41903

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

Upvotes: 2

Rasclatt
Rasclatt

Reputation: 12505

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

Upvotes: 1

Related Questions