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

Unit 7: Multidimensional Arrays



                                  Number => 25,                                                   Notes
                                ),
                           array( Title => “orchid”,
                                  Price => 1.15,
                                  Number => 7

                                )
                         );
            ?>
            It is easier to work with this array, in case you need to get a single value out of it. Necessary
            data can be easily found, if you turn to a proper cell using meaningful row and column names
            that bear logical content.  However, we are loosing the possibility to use simple for loop to view
            all columns consecutively.
            You can view outer numerically indexed $shop array using for loop. Each row of the $shop
            array is an associative array. Hence, inside the for loop you need for each loop.  Also you can
            get each element from associative array manually:



            <?php
            echo “<h1>Manual access to each element from associative array</h1>”;

            for ($row = 0; $row < 3; $row++)
            {
                echo $shop[$row][“Title”].” costs “.$shop[$row][“Price”].” and you get “.$shop[$row]
            [“Number”];

                echo “<br />”;
            }
            echo “<h1>Using foreach loop to display elements</h1>”;
            echo “<ol>”;
            for ($row = 0; $row < 3; $row++)
            {
                echo “<li><b>The row number $row</b>”;

                echo “<ul>”;
                foreach($shop[$row] as $key => $value)
                {
                    echo “<li>”.$value.”</li>”;
                }
                echo “</ul>”;
                echo “</li>”;
            }

            echo “</ol>”;
            ?>



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