PHP multidimensional array sorted by a field

To sort by another field in a multidimensional array, you can use the usort function combined with a custom comparison function.

Here is a sample code:

<?php
// 定义一个多维数组
$multidimensionalArray = array(
    array('name' => 'John', 'age' => 25),
    array('name' => 'Mary', 'age' => 30),
    array('name' => 'David', 'age' => 20)
);

// 按age字段进行排序
usort($multidimensionalArray, function($a, $b) {
    
    
    if ($a['age'] == $b['age']) {
    
    
        return 0;
    }
    return ($a['age'] < $b['age']) ? -1 : 1;
});

// 打印排序后的数组
print_r($multidimensionalArray);
?>

Executing the above code, the output will be:

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

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

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

)

In the above code, the usort function is used to sort the multidimensional array. Anonymous function is used to compare the age field of two array elements. Returns 0 if the ages of the two array elements are equal. Returns -1 if the age of the first array element is less than the age of the second array element, 1 otherwise. Finally, the sorted array is printed using the print_r function.

You can modify the comparison function to sort by different fields according to your needs.

Guess you like

Origin blog.csdn.net/qq_27487739/article/details/131527010
Recommended