Listing 2.16. Sorting an Array-Based Table Using asort()
<HTML> <HEAD><TITLE>Sorting Arrays</TITLE></HEAD> <BODY> <CENTER> <H2>Sorting Arrays using the <code>asort()</code> function</H2> <?php
$petshack['name'] = array('Rosco', 'Icky', 'Rex', 'Buster', 'Delta'); $petshack['owner'] = array('John', 'Ann', 'Cliff', 'Amy', 'Hollie'); $petshack['weight'] = array(20, 10, 3, 54, 30); $petshack['animal'] = array('Dog', 'Cat', 'Iguana', 'Dog', 'Dog');
/* Sort the weights */ asort($petshack['weight'], SORT_NUMERIC);
?> <TABLE> <TR> <TD>Pet Name</TD> <TD>Pet Owner</TD> <TD>Pet Weight</TD> <TD>Type of Animal</TD> </TR> <?php
foreach($petshack['weight'] as $key=>$weight) { echo "<TR>"; echo "<TD>{$petshack['name'][$key]}</TD><TD>{$petshack['owner'][$key]} </TD>"; echo "<TD>{$weight}</TD><TD>{$petshack['animal'][$key]}</TD>"; echo "</TR>"; }
?> </TABLE> </CENTER> </BODY> </HTML>
By changing the array passed to the asort() function (and also changing the foreach() function to loop through the array that had been sorted), this script can be modified with little difficulty to sort based on any of the four columns.
Using Arrays as a Lookup Table
Now that you have an idea of how to use arrays to develop a simple table and how array tables can be designed to provide for the maximum flexibility when dealing with sorting, let's take a look at a different type of tablethe lookup table. Unlike the tables discussed in the previous section of this chapter, a lookup table is not designed to be displayed to the user. Rather, it can be described as a reference table created and used by the PHP script to make a script more efficient or simplify a task. In this section, you'll be looking at a simple application of a lookup table. Specifically, you'll see how to implement a lookup table to create cryptograms (a puzzle game).
Tags:
Add more tags...,
|