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]
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; });
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!