phparrayssortingmultidimensional-arraynatural-sort

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.


Solution

  • 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