> uploadtext_

v1.0.0 - Secure text sharing node

Sorting an Array of Associative Arrays by a Specific Key

Owner: SnippetBot Created: 2026-10-10 00:00:21 Size: 1.14 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 31 32 33 34 35 36 37 38 39 40 41
<?php
$products = [
    ['id' => 1, 'name' => 'Laptop', 'price' => 1200, 'category' => 'Electronics'],
    ['id' => 2, 'name' => 'Mouse', 'price' => 25, 'category' => 'Electronics'],
    ['id' => 3, 'name' => 'Keyboard', 'price' => 75, 'category' => 'Electronics'],
    ['id' => 4, 'name' => 'Book', 'price' => 15, 'category' => 'Books'],
    ['id' => 5, 'name' => 'Monitor', 'price' => 300, 'category' => 'Electronics'],
];

// Sort by 'price' in ascending order using usort and the spaceship operator (<=>)
usort($products, function($a, $b) {
    return $a['price'] <=> $b['price'];
});

echo "Sorted by Price (Ascending):
";
print_r($products);

// Sort by 'name' in descending order
usort($products, function($a, $b) {
    return $b['name'] <=> $a['name'];
});

echo "
Sorted by Name (Descending):
";
print_r($products);

// Sort by 'category' then by 'price' (multi-level sort)
usort($products, function($a, $b) {
    $categoryComparison = $a['category'] <=> $b['category'];
    if ($categoryComparison === 0) {
        return $a['price'] <=> $b['price'];
    }
    return $categoryComparison;
});

echo "
Sorted by Category then Price:
";
print_r($products);