How to Use PHP’s array_multisort() Function to Sort Multiple Arrays
This article explains the PHP array_multisort() function, detailing its syntax, parameter options, and a step‑by‑step example that sorts name, age, and score arrays, followed by the resulting output and a concise summary of its practical usage.
In the PHP function library, the array_multisort() function is a powerful tool that can sort multiple arrays according to specified criteria. This article introduces how to use array_multisort() .
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>Parameter description:
1. &$array1: Required array to be sorted.
2. $array1_sort_order: Optional sorting order for the first array (SORT_ASC, SORT_DESC, or default).
3. $array1_sort_flags: Optional sorting type for the first array (SORT_REGULAR, SORT_NUMERIC, SORT_STRING).
4. $... : Optional additional arrays to be sorted.
2. Example Demonstration of array_multisort() Usage
Assume we want to sort the "name" and "age" arrays based on the students' "score" array. The following code shows how to achieve 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>The code defines three arrays ($names, $ages, $scores) and then calls array_multisort() to sort $scores in descending numeric order while reordering $names and $ages to match the new order.
Note that the SORT_NUMERIC flag specifies that $scores should be treated as numeric values.
3. Execution Result
Running the code produces the following arrays:
<code>Array
(
[0] => John
[1] => Tom
[2] => Mike
[3] => Jack
)
Array
(
[0] => 22
[1] => 25
[2] => 20
[3] => 18
)
</code>The $scores array is sorted as 90, 80, 70, 60, and the corresponding names and ages are John (22), Tom (25), Mike (20), and Jack (18).
Conclusion
The array_multisort() function is a convenient way to sort multiple arrays simultaneously, improving efficiency in PHP development. Proper use of its parameters is essential to avoid errors.
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.