[英]PHP sort multidimensional array using a specific key value
I have an array which generated using PHP as below: 我有一个使用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 )
)
the array have keys user,estimate time and destination and related values, i need to sort this array using esttime key value. 数组有密钥用户,估计时间和目的地以及相关值,我需要使用esttime键值对该数组进行排序。
i tried many ways, but couldn't able to find a way. 我尝试了很多方法,但无法找到方法。
anyone know how to sort this array using php, thank you 任何人都知道如何使用PHP排序这个数组,谢谢
You could use custom sorting usort()
in this case, then just use strtotime()
for that relative time: 在这种情况下,您可以使用自定义排序
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);
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: 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 )
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.