Output
Rating |
Title |
In their original order: |
10 |
Casablanca |
10 |
To Kill a Mockingbird |
2 |
The English Patient |
9 |
Stranger Than Fiction |
5 |
Story of the Weeping Camel |
7 |
Donnie Darko |
Sorted by title: |
10 |
Casablanca |
7 |
Donnie Darko |
5 |
Story of the Weeping Camel |
9 |
Stranger Than Fiction |
2 |
The English Patient |
10 |
To Kill a Mockingbird |
Sorted by rating: |
10 |
Casablanca |
10 |
To Kill a Mockingbird |
9 |
Stranger Than Fiction |
7 |
Donnie Darko |
5 |
Story of the Weeping Camel |
2 |
The English Patient |
Source<table border="0" cellspacing="3" cellpadding="3" align="center">
<tr>
<td><h2>Rating</h2></td>
<td><h2>Title</h2></td>
</tr>
<?php # Script 2.8 - sorting arrays
// Create the array:
$movies = array (
'Casablanca' => 10,
'To Kill a Mockingbird' => 10,
'The English Patient' => 2,
'Stranger Than Fiction' => 9,
'Story of the Weeping Camel' => 5,
'Donnie Darko' => 7
);
// Display the movies in their original order:
echo '<tr><td colspan="2"><b>In their original order:</b></td></tr>';
foreach ($movies as $title => $rating) {
echo "<tr><td>$rating</td>
<td>$title</td></tr>\n";
}
// Display the movies sorted by title:
ksort($movies);
echo '<tr><td colspan="2"><b>Sorted by title:</b></td></tr>';
foreach ($movies as $title => $rating) {
echo "<tr><td>$rating</td>
<td>$title</td></tr>\n";
}
// Display the movies sorted by rating:
arsort($movies);
echo '<tr><td colspan="2"><b>Sorted by rating:</b></td></tr>';
foreach ($movies as $title => $rating) {
echo "<tr><td>$rating</td>
<td>$title</td></tr>\n";
}
?>
</table>