Page 162 - Beginning PHP 5.3
P. 162
Part II: Learning the Language
Multi - Sorting with array_multisort()
array_multisort() lets you sort multiple related arrays at the same time, preserving the relationship
between the arrays. To use it, simply pass in a list of all the arrays you want to sort:
array_multisort( $array1, $array2, ... );
Consider the following example. Rather than storing book information in a multidimensional array, this
script stores it in three related arrays: one for the books ’ authors, one for their titles, and one for their
years of publication. By passing all three arrays to array_multisort() , the arrays are all sorted
according to the values in the first array:
$authors = array( “Steinbeck”, “Kafka”, “Tolkien”, “Dickens” );
$titles = array( “The Grapes of Wrath”, “The Trial”, “The Hobbit”, “A Tale of
Two Cities” );
$pubYears = array( 1939, 1925, 1937, 1859 );
array_multisort( $authors, $titles, $pubYears );
// Displays “Array ( [0] = > Dickens [1] = > Kafka [2] = > Steinbeck [3] = >
Tolkien )”
print_r ( $authors );
echo “ < br/ > ”;
// Displays “Array ( [0] = > A Tale of Two Cities [1] = > The Trial [2] = > The
Grapes of Wrath [3] = > The Hobbit )”
print_r ( $titles );
echo “ < br/ > ”;
// Displays “Array ( [0] = > 1859 [1] = > 1925 [2] = > 1939 [3] = > 1937 )”
print_r ( $pubYears );
Notice how the $authors array is sorted alphabetically, and the $titles and $pubYears arrays are
rearranged so that their elements are in the same order as their corresponding elements in the $authors
array. If you wanted to sort by title instead, just change the order of the arguments passed to
array_multisort() :
array_multisort( $titles, $authors, $pubYears );
In fact, array_multisort() is a bit cleverer than this. It actually sorts by the values in the first array,
then by the values in the next array, and so on. Consider this example:
$authors = array( “Steinbeck”, “Kafka”, “Steinbeck”, “Tolkien”, “Steinbeck”,
“Dickens” );
$titles = array( “The Grapes of Wrath”, “The Trial”, “Of Mice and Men”, “The
Hobbit”, “East of Eden”, “A Tale of Two Cities” );
$pubYears = array( 1939, 1925, 1937, 1937, 1952, 1859 );
array_multisort( $authors, $titles, $pubYears );
// Displays “Array ( [0] = > Dickens [1] = > Kafka [2] = > Steinbeck [3] = >
Steinbeck [4] = > Steinbeck [5] = > Tolkien )”
124
9/21/09 9:00:17 AM
c06.indd 124
c06.indd 124 9/21/09 9:00:17 AM