Tags
Asked 2 years ago
9 Jun 2021
Views 223
dilip

dilip posted

sort array by two field values in php

how to sort array by two field values in php ?
Nilesh

Nilesh
answered Apr 27 '23 00:00

In PHP, you can sort an array by two field values using th e usort() function, which allows you to define a custom comparison function.

Here is an example that demonstrates how to sort an array of associative arrays by two field values:



$myArray = array(
    array('name' => 'John', 'age' => 25),
    array('name' => 'Jane', 'age' => 30),
    array('name' => 'Bob', 'age' => 20),
    array('name' => 'Mary', 'age' => 25)
);

usort($myArray, function($a, $b) {
    // First compare by age
    $ageComparison = $a['age'] - $b['age'];
    if ($ageComparison != 0) {
        return $ageComparison;
    }

    // If the ages are the same, compare by name
    return strcmp($a['name'], $b['name']);
});

print_r($myArray);

In this example, we have an array of associative arrays with two fields : name and age . We use the usort() function to sort the array based on two criteria: first, by age in ascending order, and second, by name in ascending order.

The comparison function takes two parameters $a and $b, which represent two elements of the array to be compared. The function first compares the two elements by age and returns the result of the comparison. If the ages are the same, the function then compares the elements by name using the strcmp() function and returns the result of that comparison.

Finally, we print the sorted array using the print_r() function.

The output of the code will be:



Array
(
    [0] => Array
        (
            [name] => Bob
            [age] => 20
        )

    [1] => Array
        (
            [name] => John
            [age] => 25
        )

    [2] => Array
        (
            [name] => Mary
            [age] => 25
        )

    [3] => Array
        (
            [name] => Jane
            [age] => 30
        )

)

As you can see, the array has been sorted first by age in ascending order, and then by name in ascending order within each age group.
Post Answer