Home  >  Article  >  Backend Development  >  In PHP, how to sort an array by only certain key value pairs of the array, preserving the key names?

In PHP, how to sort an array by only certain key value pairs of the array, preserving the key names?

PHPz
PHPzOriginal
2024-05-04 09:03:01869browse

When sorting an array based on key-value pairs in PHP, you can use the uasort() function to receive a callback function to compare the key values ​​and retain the key names. For example, to sort employee records by their salary, you can use the uksort() function to extract the salary value from each element for comparison, thereby sorting the records from low to high salary.

在 PHP 中,如何仅按数组某些键值对对数组进行排序,保留键名?

Sorting an array based on key value pairs in PHP for a specific key

Sometimes, when sorting an array in PHP , we need to sort them based on specific key value pairs while preserving the key names. This article explains how to achieve this goal.

<?php

// 创建一个数组
$arr = [
    'a' => 1,
    'b' => 3,
    'c' => 2,
    'd' => 4,
];

// 使用 uasort() 函数,接收一个回调函数
uksort($arr, function($a, $b) use ($arr) {
    return $arr[$a] <=> $arr[$b];
});

// 打印排序后的数组,保留键名
print_r($arr);

Practical case: Sorting employee records by employee salary

Suppose there is an array containing employee records:

$employees = [
    'John Doe' => ['salary' => 50000],
    'Jane Smith' => ['salary' => 40000],
    'Peter Jones' => ['salary' => 60000],
];

In order to sort employee records by salary The employee records are sorted and we use an additional anonymous function to extract the salary from each element in the array:

// 按薪酬排序
uksort($employees, function($a, $b) use ($employees) {
    return $employees[$a]['salary'] <=> $employees[$b]['salary'];
});

Now, the $employees array will be sorted by employee salary from low to high , while retaining the employee name key.

The above is the detailed content of In PHP, how to sort an array by only certain key value pairs of the array, preserving the key names?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn