我有一个像这样的多维数组:
array ([0] => array ([id] => 1 [name] => john doe [title] => Mr [days] => 10)
[1] => array ([id] => 2 [name] => Joe Smith [title] => Dr [days] => 22)
[2] => array ([id] => 3 [name] => John Jones [title] => Mr [days] => 3))
我需要对内部数组进行排序,以便按日期键以自然顺序返回数据。
I.E喜欢这样:
array ([2] => array ([id] => 3 [name] => John Jones [title] => Mr [days] => 3)
[0] => array ([id] => 1 [name] => john doe [title] => Mr [days] => 10)
[1] => array ([id] => 2 [name] => Joe Smith [title] => Dr [days] => 22))
我认为我需要的是一个通过$ key将natsort应用于多维数组的函数,但到目前为止,我还没有找到任何除标准排序之外的任何函数。
任何帮助?
答案 0 :(得分:3)
你想要的是usort。
您可以编写回调来为您进行比较:
usort($data, function($a, $b) {
return ($a['days'] > $b['days'])
? 1
: ($a['days'] < $b['days'])
? -1
: 0;
});
免责声明:您需要PHP 5.3.x才能使用此功能,否则您必须使用create_function或预定义比较功能。
答案 1 :(得分:0)
有点不同的做法:
$days = array();
foreach($array as $key => $val) {
$days[$key] = $val['days'];
}
array_multisort($days, $array); //$array being your input array
<强>结果:强>
Array
(
[0] => Array
(
[id] => 3
[name] => Jay Doe
[title] => Mr
[days] => 3
)
[1] => Array
(
[id] => 1
[name] => John Doe
[title] => Mr
[days] => 10
)
[2] => Array
(
[id] => 2
[name] => Joe Doe
[title] => Mr
[days] => 22
)
)
答案 2 :(得分:0)
以下内容对我有用
usort($array, function($a, $b) {
return strnatcasecmp($a['days'], $b['days']);
});
从这里找到:-https://learntech.imsu.ox.ac.uk/blog/php-naturally-sorting-multidimension-arrays-by-string-values/
希望有人会发现这很有用。