PHP and MySQL Web Development - P24

PHP and MySQL Web Development - P24: PHP and MySQL Web Development teaches the reader to develop dynamic, secure, commercial Web sites. Using the same accessible, popular teaching style of the first edition, this best-selling book has been updated to reflect the rapidly changing landscape of MySQL and PHP. | 82 Chapter 3 Using Arrays Sorting 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. User Defined Sorts Here is the definition of a two-dimensional array we used array stores Bob s 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 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 will examine writing functions in detail in Chapter 5 Reusing Code and Writing Functions but here is a brief introduction. We define a function using the keyword need to give the function a name. Names should be meaningful so we ll call it compare . Many functions take parameters or arguments. Our compare function takes two one called x and one called y. The purpose of this function is to take two values and determine their order. Sorting .

Không thể tạo bản xem trước, hãy bấm tải xuống
TỪ KHÓA LIÊN QUAN
TÀI LIỆU MỚI ĐĂNG
16    439    9    26-04-2024
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.