note 4772 modified in sort by ronabop
| From: | ronabop@php.net | Date: | Wed, 13 Sep 2000 17:45:38 +0000 |
| Subject: | note 4772 modified in sort by ronabop | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-4851@lists.php.net to get a copy of this message | ||
What you really want is asort(). The neat thing about PHP arrays is that even though they have a
traditional numerical index, they are not defined by it. What I mean by this is if you define an
array $data[], then $data[2] does not necessarily exist between $data[1] and $data[3].
So if you asort() by the artist name and then use each() to recover the array elements in the order
they exist(rather than an incremental loop which ties you to their arbitrary numerical key), you can
sort your data by any dimension of your array. Try this out:
$data[0][1]='Title 2';
$data[0][2]='Title 1';
$data[0][0]='Title 3';
$data[1][1]='Barney';
$data[1][0]='Charlie';
$data[1][2]='Al';
$data[2][2]='Sing the song of Al';
$data[2][1]='Jam with Barney';
$data[2][0]='Charlie Rocks';
while (list($key) = each($data[1])) {
print
$data[0][$key].",".$data[1][$key].",".$data[2][$key]."<p>";
}
asort($data[1]);
while (list($key) = each($data[1])) {
print
$data[0][$key].",".$data[1][$key].",".$data[2][$key]."<p>";
}
The interesting part is that the first, UNSORTED array doesn't come out in numerical order,
because it wasn't put in that way. If you asort($data[2]) you'll sort by lyrics, and so
on. Just make sure you remember to each() by the same dimension as you asort().
http://www.php.net/manual/function.sort.php