0

我有一个像这样的多维数组:

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

我需要对内部数组进行排序,以便按天键以自然顺序返回数据。

像这样的IE:

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 应用于多维数组的函数,但到目前为止,我还没有找到除标准排序之外的任何函数。

有什么帮助吗?

4

3 回答 3

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或预定义比较函数。

于 2010-09-13T11:06:09.593 回答
1

以下对我有用,

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/

希望有人会发现这很有用。

于 2019-12-27T11:19:36.867 回答
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
        )

)
于 2010-09-13T11:32:19.860 回答