首页  >  文章  >  后端开发  >  如何使用 usort 和自定义比较函数按特定键对多维数组进行排序?

如何使用 usort 和自定义比较函数按特定键对多维数组进行排序?

Linda Hamilton
Linda Hamilton原创
2024-10-20 19:07:02476浏览

How to Sort Multidimensional Arrays by a Specific Key Using usort and Custom Comparison Function?

按键对多维数组进行排序

使用多维数组时的一个常见任务是需要根据特定键对它们进行排序。例如,考虑以下数组:

Array (
[0] => Array
    (
        [iid] => 1
        [invitee] => 174
        [nid] => 324343
        [showtime] => 2010-05-09 15:15:00
        [location] => 13
        [status] => 1
        [created] => 2010-05-09 15:05:00
        [updated] => 2010-05-09 16:24:00
    )

[1] => Array
    (
        [iid] => 1
        [invitee] => 220
        [nid] => 21232
        [showtime] => 2010-05-09 15:15:00
        [location] => 12
        [status] => 0
        [created] => 2010-05-10 18:11:00
        [updated] => 2010-05-10 18:11:00
    ))

要按 [status] 键对此数组进行排序,您可以使用 usort 函数以及自定义比较函数:

// Define a comparison function
function cmp($a, $b) {
    if ($a['status'] == $b['status']) {
        return 0;
    }
    return ($a['status'] < $b['status']) ? -1 : 1;
}

// Sort the array using the custom comparison function
usort($array, "cmp");

通过定义 cmp 函数,您可以指定在排序期间应如何比较元素。在这种情况下,它比较两个元素的 [status] 键,如果 $a['status'] 小于 $b['status'],则返回 -1,如果相等则返回 0,否则返回 1。

usort 函数根据比较函数的输出按升序排列数组元素。这允许您按所需的键对多维数组进行排序,在本例中为 [status]。

以上是如何使用 usort 和自定义比较函数按特定键对多维数组进行排序?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn