05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Example 5-3. Sorting arrays (continued)<br />

<br />

Values :<br />

<br />

<br />

<br />

<br />

<br />

Natural-Order Sorting<br />

<strong>PHP</strong>’s built-in sort functions correctly sort strings and numbers, but they don’t correctly<br />

sort strings that contain numbers. For example, if you have the filenames<br />

ex10.php, ex5.php, and ex1.php, the normal sort functions will rearrange them in<br />

this order: ex1.php, ex10.php, ex5.php. To correctly sort strings that contain numbers,<br />

use the natsort( ) and natcasesort( ) functions:<br />

$output = natsort(input);<br />

$output = natcasesort(input);<br />

Sorting Multiple Arrays at Once<br />

The array_multisort( ) function sorts multiple indexed arrays at once:<br />

array_multisort(array1 [, array2, ... ]);<br />

Pass it a series of arrays and sorting orders (identified by the SORT_ASC or SORT_DESC<br />

constants), and it reorders the elements of all the arrays, assigning new indexes. It is<br />

similar to a join operation on a relational database.<br />

Imagine that you have a lot of people, and several pieces of data on each person:<br />

$names = array('Tom', 'Dick', 'Harriet', 'Brenda', 'Joe');<br />

$ages = array(25, 35, 29, 35, 35);<br />

$zips = array(80522, '02140', 90210, 64141, 80522);<br />

The first element of each array represents a single record—all the information known<br />

about Tom. Similarly, the second element constitutes another record—all the information<br />

known about Dick. The array_multisort( ) function reorders the elements of<br />

the arrays, preserving the records. That is, if Dick ends up first in the $names array<br />

after the sort, the rest of Dick’s information will be first in the other arrays too. (Note<br />

that we needed to quote Dick’s zip code to prevent it from being interpreted as an<br />

octal constant.)<br />

Here’s how to sort the records first ascending by age, then descending by zip code:<br />

array_multisort($ages, SORT_ASC, $zips, SORT_DESC, $names, SORT_ASC);<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

Sorting | 133

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!