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],
]
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],
]
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 */
);
fn (...) => ...
Arrow Functions (PHP 7.4)function name (): int
Return type declarations (PHP 7.0)<=>
Spaceship Operator (PHP 7.0)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")
Compare this with the answer of one of the questions duplicates.
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
)
)
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);