按第一列对2d数组(列名不一致)进行排序


Sort 2d array (with inconsistent column names) by first column

如何根据每行中的第一个值对数组或行进行排序?

$array = [
    ['item1' => 80],
    ['item2' => 25],
    ['item3' => 85],
];

期望输出:

[
    ['item2' => 25],
    ['item1' => 80],
    ['item3' => 85],
]

您需要使用usort,这是一个通过用户定义的函数对数组进行排序的函数。类似于:

usort(
    $yourArray, 
    fn(array $a, array $b): int /* (1),(2) range: -1 ... 1 */
    => reset($a) /* get the first array elements from $a */ 
       <=>  /* (3) <--- the spaceship operator */
       reset($b) /* and from $b for comparison */
);
  1. fn (...) => ...箭头函数(PHP 7.4)
  2. function name (): int返回类型声明(PHP 7.0)
  3. <=>飞船操作员(PHP 7.0)

(查看3v4l.org上的直播)


用更老、更老的PHP表达:

function cmp($a, $b)
{
    $a = reset($a); // get the first array elements
    $b = reset($b); // for comparison.
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}
usort($yourArray, "cmp")

(查看3v4l.org上的直播)

将其与其中一个重复问题的答案进行比较。


您需要使用usort

$array = array (
  0 =>
  array (
    'item1' => 80,
  ),
  1 =>
  array (
    'item2' => 25,
  ),
  2 =>
  array (
    'item3' => 85,
  ),
);
function my_sort_cmp($a, $b) {
    reset($a);
    reset($b);
    return current($a) < current($b) ? -1 : 1;
}
usort($array, 'my_sort_cmp');
print_r($array);

输出:

(
    [0] => Array
        (
            [item2] => 25
        )
    [1] => Array
        (
            [item1] => 80
        )
    [2] => Array
        (
            [item3] => 85
        )
)

使用现代PHP,使用箭头函数和宇宙飞船运算符的语法优势调用usort()。使用current()reset()访问每行的第一个元素。

代码:(演示)

usort($array, fn($a, $b) => current($a) <=> current($b));

具有较少总函数调用的等价物:(演示)

array_multisort(array_map('current', $array), $array);