PHP使用特定的键值对多维数组进行排序


PHP sort multidimensional array using a specific key value

我有一个使用PHP生成的数组,如下所示:

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

该数组具有关键字user、估计时间和目的地以及相关值,我需要使用esttime关键字值对该数组进行排序。

我试了很多方法,但都找不到办法。

任何知道如何使用php对这个数组进行排序的人,感谢

在这种情况下,您可以使用自定义排序usort(),然后只使用相对时间的strtotime()

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

样本输出

一种方法是生成一个新数组:

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

print_r($new)在之后应该是这样的

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