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

Unit 7: Multidimensional Arrays



            The array_search( ) function also takes the optional third strict argument, which requires the   Notes
            types of the value being searched for and the value in the array to match.



                      Develop a PHP program to build a table with the iterator functions.

            7.5 Sorting of Multidimensional Arrays

            Sorting  arrays  with  more  than  one  dimension,  or  by  something  other  than  alphabetical  or
            numerical order, is more complicated. PHP knows how to compare two numbers or two text
            strings, but in a multidimensional array, each element is an array. PHP does not know how to
            compare two arrays, so you need to create a method to compare them. Most of the time, the
            order of the words or numbers is fairly obvious but for complicated objects, it becomes more
            problematic.

            7.5.1 User Defined Sorts
            Here is the definition of a two-dimensional array we used earlier. This array stores three products
            with a code, a description, and a price for each.
            $products = array( array( ‘TIR’, ‘Tires’, 100 ),
                      array( ‘OIL’, ‘Oil’, 10 ),

                      array( ‘SPK’, ‘Spark Plugs’, 4 ) );
            If we sort this array, what order will the values end up in? Because we know what the contents
            represent, there are at least two useful orders. We might want the products sorted into alphabetical
            order using the description or by numeric order by the price. Either result is possible, but we
            need to use the function usort() and tell PHP how to compare the items. To do this, we need to
            write our own comparison function.
            The following code sorts this array into alphabetical order using the second column in the array
            the description.
            function compare($x, $y)
            {

             if ( $x[1] == $y[1] )
              return 0;

             else if ( $x[1] < $y[1] )
              return -1;
             else

              return 1;
            }
            usort($products, ‘compare’);

            So far in this book, we have called a number of the built-in PHP functions. To sort this array,
            we have defined a function of our own.

            We define a function using the keyword function. We need to give the function a name. Names
            should be meaningful, so we’ll call it compare (). Many functions take parameters or arguments.



                                             LOVELY PROFESSIONAL UNIVERSITY                                   161
   162   163   164   165   166   167   168   169   170   171   172