Using PHP's array_multisort() Function to Sort Multiple Arrays
This article explains the syntax, parameters, and practical example of PHP's array_multisort() function, demonstrating how to sort multiple related arrays such as names, ages, and scores in a single operation.
1. Syntax of array_multisort()
<code>array_multisort ( array &$array1 [, mixed $array1_sort_order = SORT_ASC [, mixed $array1_sort_flags = SORT_REGULAR [, mixed $... [, mixed $... ]]]]) : bool</code>Parameters:
1. &$array1 : required, the array to be sorted.
2. $array1_sort_order : optional, sorting order for the first array; can be SORT_ASC (ascending), SORT_DESC (descending), or omitted (default order).
3. $array1_sort_flags : optional, sorting type for the first array; can be SORT_REGULAR , SORT_NUMERIC , or SORT_STRING .
4. $... : optional, additional arrays to be sorted together.
2. Example usage of array_multisort()
Assume we want to sort the "name" and "age" arrays according to the "score" array. The following code demonstrates this:
<code>$names = array('Tom', 'Jack', 'Mike', 'John');
$ages = array('25', '18', '20', '22');
$scores = array('80', '60', '70', '90');
array_multisort($scores, SORT_DESC, SORT_NUMERIC, $names, $ages);
</code>Explanation: The three arrays are defined first. array_multisort() is then called with $scores as the primary array, sorted in descending numeric order. The $names and $ages arrays are passed as additional arrays, so they are reordered to match the sorted order of $scores .
Note: The SORT_NUMERIC flag ensures that the scores are compared as numbers rather than strings.
Result
<code>Array
(
[0] => John
[1] => Tom
[2] => Mike
[3] => Jack
)
Array
(
[0] => 22
[1] => 25
[2] => 20
[3] => 18
)
</code>From the output we can see that the scores are ordered 90, 80, 70, 60, and the corresponding names and ages are John (22), Tom (25), Mike (20), and Jack (18).
3. Conclusion
The array_multisort() function is a convenient tool for sorting multiple arrays simultaneously, making data handling more efficient in PHP development. When using it, be mindful of the parameter order and flags to avoid unexpected results.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.