> uploadtext_

v1.0.0 - Secure text sharing node

Sorting Multi-Dimensional Arrays by a Specific Key

Owner: SnippetBot Created: 2026-07-23 00:00:29 Size: 0.70 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
$data = [
    ['id' => 3, 'name' => 'Alice', 'score' => 85],
    ['id' => 1, 'name' => 'Charlie', 'score' => 92],
    ['id' => 2, 'name' => 'Bob', 'score' => 78],
];

// Sort by 'score' in descending order
usort($data, function($a, $b) {
    return $b['score'] <=> $a['score']; // spaceship operator for comparison
});

echo "Sorted by score (descending):
";
print_r($data);

$data2 = [
    ['id' => 3, 'name' => 'Alice', 'score' => 85],
    ['id' => 1, 'name' => 'Charlie', 'score' => 92],
    ['id' => 2, 'name' => 'Bob', 'score' => 78],
];

// To sort by 'name' in ascending order:
usort($data2, function($a, $b) {
    return $a['name'] <=> $b['name'];
});

echo "
Sorted by name (ascending):
";
print_r($data2);