Php sort array by nested value

Sorting PHP Array by Nested Value

In PHP, you can sort an array by a nested value using the usort() function along with a custom comparison function.

Let’s take an example of an array with nested values representing students and their grades:

        $students = [
            ["name" => "John", "grade" => 85],
            ["name" => "Alice", "grade" => 92],
            ["name" => "Bob", "grade" => 78],
            ["name" => "Carol", "grade" => 90]
        ];
    

We want to sort this array based on the “grade” in ascending order. To do this, we’ll define a custom comparison function that compares the “grade” values of two elements.

        function compareGrades($a, $b) {
            return $a["grade"] - $b["grade"];
        }
    

Now, we can use the usort() function to sort the array using our custom comparison function:

        usort($students, "compareGrades");
    

After sorting, the $students array will be in ascending order based on the “grade” value:

        [
            ["name" => "Bob", "grade" => 78],
            ["name" => "John", "grade" => 85],
            ["name" => "Carol", "grade" => 90],
            ["name" => "Alice", "grade" => 92]
        ]
    

You can also sort the array in descending order by modifying the return statement in the custom comparison function:

        function compareGrades($a, $b) {
            return $b["grade"] - $a["grade"];
        }
    

Using this modified comparison function with usort() will sort the array in descending order based on the “grade” value.

Leave a comment