0

How can I sort an array or rows by the first value in each row?

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

Desired output:

[
    ['item2' => 25],
    ['item1' => 80],
    ['item3' => 85],
]
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
gary
  • 1
  • 1
    Or this one: http://stackoverflow.com/questions/2426917/how-do-i-sort-a-multidimensional-array-by-one-of-the-fields-of-the-inner-array-in – hakre Jun 30 '11 at 12:55

3 Answers3

1

You need to use usort, a function that sorts arrays via a user defined function. Something like:

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 (...) => ... Arrow Functions (PHP 7.4)
  2. function name (): int Return type declarations (PHP 7.0)
  3. <=> Spaceship Operator (PHP 7.0)

(see it live on 3v4l.org)


Expressed in older, well-aged 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")

(see it live on 3v4l.org)

Compare this with the answer of one of the questions duplicates.


hakre
  • 193,403
  • 52
  • 435
  • 836
0

You need to use 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);

Output:

(
    [0] => Array
        (
            [item2] => 25
        )

    [1] => Array
        (
            [item1] => 80
        )

    [2] => Array
        (
            [item3] => 85
        )

)
Dogbert
  • 212,659
  • 41
  • 396
  • 397
0

With modern PHP, call usort() with the syntactic sugary goodness of an arrow function and the spaceship operator. Access the first element of each row with current() or reset().

Code: (Demo)

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

The equivalent with fewer total function calls: (Demo)

array_multisort(array_map('current', $array), $array);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136