Sorting multidimensional arrays
Sorting arrays is easy using PHP, thanks to the sort(), ksort(), and related functions. You can sort a one-dimensional array by key, by value, in reverse order, etc. But these functions will not work on multidimensional arrays (not as you'd probably like, at least).
Say you have an array defined like so: $a = array (
array ('keyl' => 940, 'key2' => 'blah'), array ('keyl' => 23, 'key2' => 'this'), array ('keyl' => 894, 'key2' => 'that') );
This is a simple two-dimensional array (an array whose elements are also arrays) that you might need to sort using key1 (a numeric sort) or key2 (an alphabetical sort). To sort a multidimensional array, you define your own sort function and then tell PHP to use that function via the usort(), uasort(), or uksort() function. The function you define must take exactly two arguments and return a value indicating which should come first.
- Figure 1.1 One use of multidimensional arrays will be to create a nested to-do list.
|
eoo |
Mozilla Firefox |
CD | |
|
Array | |||
|
[0] |
■> Array 1 | ||
|
[keyl] |
23 | ||
|
) |
this | ||
|
[11 |
■> Array j | ||
|
[keyl1 |
S94 | ||
|
) |
■ > |
that | |
|
121 |
■> Array j | ||
|
[keyl] |
■ > |
940 | |
|
) |
blah | ||
|
) | |||
|
eoo |
Mozilla Firefox |
CD | |
|
Iteration |
: 23 vs. 940 | ||
|
Iteration 2: 894 vs. 23 | |||
|
Iteration 3:940 vs. 23 | |||
|
Iteration 4: 894 vs. 940 | |||
|
Array | |||
|
[01 |
■> Array | ||
|
[keyl] |
23 | ||
|
) |
this | ||
|
HI |
■> Array | ||
|
[keylJ |
■ > |
894 | |
|
) |
that | ||
|
[21 |
■> Array | ||
|
[keyl] |
■ > |
940 | |
|
) |
blah | ||
|
) |
A | ||
|
OOO |
Mozilla Firefox |
CD | |
|
Array { | |||
|
mi |
■> Array | ||
|
f keyl] |
940 | ||
|
) |
■ > |
blah | |
|
(M |
■> Array | ||
|
f keyl] |
■ > |
894 | |
|
1 |
■ > |
that | |
|
[21 |
■> Array r | ||
|
f keyl] |
- > |
23 | |
|
) |
- > |
this | |
|
) | |||
Figure 1.4 An alphabetical sort on the example array using key2.
To sort the preceding array on the first key, the sorting function would like this: function mysort1 ($x, $y) {
Then the PHP code would use this function by doing:
Figure 1.2 shows the same array at this point.
PHP will continue sending the inner arrays to this function so that they may be sorted. If you want to see this in detail, print the values being compared in the function (Figure 1.3).
The usort() function sorts by values and does not maintain the keys (for the outermost array). If you used uasort(), the keys would be maintained, and if you used uksort(), the sort would be based upon the keys.
To sort on the second key in the preceding example, you would want to compare two strings. That code would be (Figure 1.4 shows the result): function mysort2 ($x, $y) {
return strcasecmp($x['key2'],
Or you could just use strcmpO, to perform a case-sensitive sort.
To see this in action for yourself, let's run through an example.
Figure 1.4 An alphabetical sort on the example array using key2.
Post a comment