Home > Backend Development > PHP Tutorial > How to Sort a PHP Array Based on a Custom Order?

How to Sort a PHP Array Based on a Custom Order?

Patricia Arquette
Release: 2024-12-24 08:11:15
Original
952 people have browsed it

How to Sort a PHP Array Based on a Custom Order?

Custom Order Array Sorting in PHP

Sorting arrays in PHP is typically done through comparison-based algorithms. However, there are situations where you need to sort arrays based on a predefined custom order.

Consider an array of arrays where each sub-array contains two keys: "id" and "title." You want to sort the main array in a specific order, such as:

[3452342, 5867867, 7867867, 1231233]
Copy after login

To achieve this, you can utilize the usort() function. This function allows you to specify a comparison function that defines how the array elements are compared.

In this case, the comparison function uses a closure to compare the positions of the "id" values in the custom order array ($order):

usort($array, function ($a, $b) use ($order) {
    $pos_a = array_search($a['id'], $order);
    $pos_b = array_search($b['id'], $order);
    return $pos_a - $pos_b;
});
Copy after login

The comparison function assigns the positions of the "id" values in the $order array to $pos_a and $pos_b. It then subtracts these positions to determine the order ($a comes before $b if $pos_a is less than $pos_b).

By using the custom order array and the comparison function, you can effectively sort your array of arrays in the predefined order.

The above is the detailed content of How to Sort a PHP Array Based on a Custom Order?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template