Page 154 - Open Soource Technologies 304.indd
P. 154

Web Technologies-I



                   Notes         This example shows that now $shop array, in fact, contains three arrays. As you remember,
                                 to access data in one-dimensional array you have to point to array name and index. The
                                 same is true in regards to a two-dimensional array, with one exception: each element has two
                                 indexes—row and column.
                                 To display elements of this array we could have organized manual access to each element or
                                 make it by putting for loop inside another for loop:
                                        Example:

                                 <?php
                                 echo “<h1>Manual access to each element</h1>”;
                                 echo $shop[0][0].” costs “.$shop[0][1].” and you get “.$shop[0][2].”<br />”;

                                 echo $shop[1][0].” costs “.$shop[1][1].” and you get “.$shop[1][2].”<br />”;
                                 echo $shop[2][0].” costs “.$shop[2][1].” and you get “.$shop[2][2].”<br />”;
                                 echo “<h1>Using loops to display array elements</h1>”;

                                 echo “<ol>”;
                                 for ($row = 0; $row < 3; $row++)
                                 {
                                     echo “<li><b>The row number $row</b>”;
                                     echo “<ul>”;

                                     for ($col = 0; $col < 3; $col++)
                                     {
                                         echo “<li>”.$shop[$row][$col].”</li>”;
                                     }

                                     echo “</ul>”;
                                     echo “</li>”;
                                 }
                                 echo “</ol>”;
                                 ?>

                                 Perhaps, instead of the column numbers you prefer to create their names. For this purpose,
                                 you can use associative arrays.  The following code will store the same set of flowers using
                                 column names:
                                        Example:

                                 <?php
                                 $shop = array( array( Title => “rose”,
                                                       Price => 1.25,
                                                       Number => 15

                                                     ),
                                                array( Title => “daisy”,
                                                       Price => 0.75,


        148                               LOVELY PROFESSIONAL UNIVERSITY
   149   150   151   152   153   154   155   156   157   158   159