且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP 按子数组值对数组进行排序

更新时间:2023-02-05 14:28:39

使用 usort.

function cmp_by_optionNumber($a, $b) {
  return $a["optionNumber"] - $b["optionNumber"];
}

...

usort($array, "cmp_by_optionNumber");

在 PHP ≥5.3 中,您应该使用 匿名函数:

usort($array, function ($a, $b) {
    return $a['optionNumber'] - $b['optionNumber'];
});

请注意,上面的两个代码都假定 $a['optionNumber'] 是一个整数.使用 @St.约翰约翰逊的解决方案如果它们是字符串.

Note that both code above assume $a['optionNumber'] is an integer. Use @St. John Johnson's solution if they are strings.

在 PHP ≥7.0 中,使用 飞船操作符<=> 而不是减法,以防止溢出/截断问题.

In PHP ≥7.0, use the spaceship operator <=> instead of subtraction to prevent overflow/truncation problems.

usort($array, function ($a, $b) {
    return $a['optionNumber'] <=> $b['optionNumber'];
});