- PHP

How to sort associative arrays by given key value in PHP

Use array_multisort() and array_column() functions.

array_multisort(array_column($array, 'yourKey'), SORT_ASC, $array);

Example:

<?php

$products = [
    ['name' => 'Smartphone', 'price' => 699],
    ['name' => 'Orange', 'price' => 0.39],
    ['name' => 'Banana', 'price' => 0.69],
    ['name' => 'Book', 'price' => 8.99],
    ['name' => 'Shoes', 'price' => 45],
];


array_multisort(array_column($products, 'price'), SORT_ASC, $products);

print_r($products);

Output:


Array
(
    [0] => Array
        (
            [name] => Orange
            [price] => 0.39
        )

    [1] => Array
        (
            [name] => Banana
            [price] => 0.69
        )

    [2] => Array
        (
            [name] => Book
            [price] => 8.99
        )

    [3] => Array
        (
            [name] => Shoes
            [price] => 45
        )

    [4] => Array
        (
            [name] => Smartphone
            [price] => 699
        )

)