• Tidak ada hasil yang ditemukan

Sorting Arrays

Dalam dokumen Beginning PHP and MySQL 5 (Halaman 153-159)

To be sure, data sorting is a central topic of computer science. Anybody who’s taken an entry- level programming class is well aware of sorting algorithms such as bubble, heap, shell, and quick. This subject rears its head so often during daily programming tasks that the process of sorting data is as common as creating an if conditional or a while loop. PHP facilitates the process by offering a multitude of useful functions capable of sorting arrays in a variety of manners. Those functions are introduced in this section.

Tip

By default, PHP’s sorting functions sort in accordance with the rules as specified by the English language. If you need to sort in another language, say French or German, you’ll need to modify this default behavior by setting your locale using the setlocale() function.

sort()

void sort(array target_array [, int sort_flags])

The sort() function sorts the target_array, ordering elements from lowest to highest value.

Note that it doesn’t return the sorted array. Instead, it sorts the array “in place,” returning nothing, regardless of outcome. The optional sort_flags parameter modifies the function’s default behavior in accordance with its assigned value:

• SORT_NUMERIC: Sort items numerically. This is useful when sorting integers or floats.

• SORT_REGULAR: Sort items by their ASCII value. This means that B will come before a, for instance. A quick search online will produce several ASCII tables, so one isn’t reproduced in this book.

• SORT_STRING: Sort items in a fashion that might better correspond with how a human might perceive the correct order. See natsort() for further information about this matter, introduced later in this section.

Consider an example. Suppose you wanted to sort exam grades from lowest to highest:

$grades = array(42,57,98,100,100,43,78,12);

sort($grades);

print_r($grades);

The outcome looks like this:

Array ( [0] => 12 [1] => 42 [2] => 43 [3] => 57 [4] => 78 [5] => 98 [6] => 100 [7] => 100 )

It’s important to note that key/value associations are not maintained. Consider the following example:

$states = array("OH" => "Ohio", "CA" => "California", "MD" => "Maryland");

sort($states);

print_r($states);

Here’s the output:

Array ( [0] => California [1] => Maryland [2] => Ohio )

To maintain these associations, use asort(), introduced later in this section.

natsort()

void natsort(array target_array)

The natsort() function is intended to offer a sorting mechanism comparable to the mechanisms that people normally use. The PHP manual offers an excellent example, borrowed here, of what our innate sorting strategies entail. Consider the following items: picture1.jpg, picture2.jpg, picture10.jpg, picture20.jpg. Sorting these items using typical algorithms results in the following ordering:

picture1.jpg, picture10.jpg, picture2.jpg, picture20.jpg

Certainly not what you might have expected, right? The natsort() function resolves this dilemma, sorting the target_array in the order you would expect, like so:

picture1.jpg, picture2.jpg, picture10.jpg, picture20.jpg

natcasesort()

void natcasesort(array target_array)

The function natcasesort() is functionally identical to natsort(), except that it is case insensitive.

Returning to the file-sorting dilemma raised in the natsort() section, suppose that the pictures were named like this: Picture1.JPG, picture2.jpg, PICTURE10.jpg, picture20.jpg. The natsort() function would do its best, sorting these items like so:

PICTURE10.jpg, Picture1.JPG, picture2.jpg, picture20.jpg

The natcasesort() function resolves this idiosyncrasy, sorting as you might expect:

Picture1.jpg, PICTURE10.jpg, picture2.jpg, picture20.jpg

rsort()

void rsort(array target_array [, int sort_flags])

The rsort() function is identical to sort(), except that it sorts array items in reverse (descending) order. An example follows:

$states = array("Ohio","Florida","Massachusetts","Montana");

sort($states);

print_r($states)

// Array ( [0] => Ohio [1] => Montana [2] => Massachusetts [3] => Florida ) If the optional sort_flags parameter is included, then the exact sorting behavior is determined by its value, as explained in the sort() section.

asort()

void asort(array target_array [,integer sort_flags])

The asort() function is identical to sort(), sorting the target_array in ascending order, except that the key/value correspondence is maintained. Consider an array that contains the states in the order in which they joined the Union:

$state[0] = "Delaware";

$state[1] = "Pennsylvania";

$state[2] = "New Jersey";

Sorting this array using sort() causes the associative correlation to be lost, which is probably a bad idea. Sorting using sort() produces the following ordering:

Array ( [0] => Delaware [1] => New Jersey [2] => Pennsylvania )

However, sorting with asort() produces:

Array ( [0] => Delaware [2] => New Jersey [1] => Pennsylvania )

If you use the optional sort_flags parameter, the exact sorting behavior is determined by its value, as described in the sort() section.

array_multisort()

boolean array_multisort(array array [, mixed arg [, mixed arg2...]])

The array_multisort() function can sort several arrays at once, and can sort multidimensional arrays in a number of fashions, returning TRUE on success and FALSE otherwise. It takes as input one or more arrays, each of which can be followed by flags that determine sorting behavior.

There are two categories of sorting flags: order and type. Each flag is described in Table 5-1.

Consider an example. Suppose that you want to sort the surname column of a multidimen- sional array consisting of staff information. To ensure that the entire name (given-name surname) is sorted properly, you would then sort by the given name:

Table 5-1. array_multisort() Flags

Flag Type Purpose

SORT_ASC Order Sort in ascending order

SORT_DESC Order Sort in descending order

SORT_REGULAR Type Compare items normally

SORT_NUMERIC Type Compare items numerically

SORT_STRING Type Compare items as strings

<?php

$staff["givenname"][0] = "Jason";

$staff["givenname"][1] = "Manny";

$staff["givenname"][2] = "Gary";

$staff["givenname"][3] = "James";

$staff["surname"][0] = "Gilmore";

$staff["surname"][1] = "Champy";

$staff["surname"][2] = "Grisold";

$staff["surname"][3] = "Gilmore";

$res = array_multisort($staff["surname"],SORT_STRING,SORT_ASC, $staff["givenname"],SORT_STRING,SORT_ASC);

print_r($staff);

?>

This returns the following:

Array ( [givenname] => Array ( [0] => Manny [1] => James [2] => Jason [3] => Gary ) [surname] => Array ( [0] => Champy [1] => Gilmore [2] =>

Gilmore [3] => Grisold ) )

arsort()

void arsort(array array [, int sort_flags])

Like asort(), arsort() maintains key/value correlation. However, it sorts the array in reverse order. An example follows:

$states = array("Delaware","Pennsylvania","New Jersey");

arsort($states);

print_r($states);

// Array ( [1] => Pennsylvania [2] => New Jersey [0] => Delaware )

If the optional sort_flags parameter is included, the exact sorting behavior is determined by its value, as described in the sort() section.

ksort()

integer ksort(array array [,int sort_flags])

The ksort() function sorts the input array array by its keys, returning TRUE on success and FALSE otherwise. If the optional sort_flags parameter is included, then the exact sorting behavior is determined by its value, as described in the sort() section. Keep in mind that the behavior will be applied to key sorting but not to value sorting.

krsort()

integer krsort(array array [,int sort_flags])

The krsort() function operates identically to ksort(), sorting by key, except that it sorts in reverse (descending) order.

usort()

void usort(array array, callback function_name)

The usort() function offers a means for sorting an array by using a user-defined comparison algorithm, embodied within a function. This is useful when you need to sort data in a fashion not offered by one of PHP’s built-in sorting functions.

The user-defined function must take as input two arguments and must return a negative integer, zero, or a positive integer, respectively, based on whether the first argument is less than, equal to, or greater than the second argument. Not surprisingly, this function must be made available to the same scope in which usort() is being called.

A particularly applicable example of where usort() comes in handy involves the ordering of American-format dates (month-day-year, as opposed to day-month-year ordering used by most other countries). Suppose that you want to sort an array of dates in ascending order:

<?php

$dates = array('10-10-2003', '2-17-2002', '2-16-2003', '1-01-2005', '10-10-2004');

sort($dates);

// Array ( [0] => 10-01-2002 [1] => 10-10-2003 [2] => 2-16-2003 [3] => 8-18-2002 ) natsort($dates);

// Array ( [2] => 2-16-2003 [3] => 8-18-2002 [1] => 10-01-2002 [0] => 10-10-2003 ) function DateSort($a, $b) {

// If the dates are equal, do nothing.

if($a == $b) return 0;

// Disassemble dates

list($amonth, $aday, $ayear) = explode('-',$a);

list($bmonth, $bday, $byear) = explode('-',$b);

// Pad the month with a leading zero if leading number not present $amonth = str_pad($amonth, 2, "0", STR_PAD_LEFT);

$bmonth = str_pad($bmonth, 2, "0", STR_PAD_LEFT);

// Pad the day with a leading zero if leading number not present $aday = str_pad($aday, 2, "0", STR_PAD_LEFT);

$bday = str_pad($bday, 2, "0", STR_PAD_LEFT);

// Reassemble dates

$a = $ayear . $amonth . $aday;

$b = $byear . $bmonth . $bday;

// Determine whether date $a > $date b return ($a > $b) ? 1 : -1;

}

usort($dates, 'DateSort');

print_r($dates);

?>

This returns the desired result:

Array ( [0] => 8-18-2002 [1] => 10-01-2002 [2] => 2-16-2003 [3] => 10-10-2003 )

Dalam dokumen Beginning PHP and MySQL 5 (Halaman 153-159)