TAILIEUCHUNG - Phát triển web với PHP và MySQL - p 11

Using Arrays CHAPTER 3 75 This line uses each() to take the current element from $prices, return it as an array, and make the next element current. It also uses list() to turn the 0 and 1 elements from the array returned by each() into two new variables called $product and $price. We can loop through the entire $prices array, echoing the contents using this short script. while ( list( $product, $price ) = each( $prices ) ) echo “$product - $price”; This has the same output as the previous script, but is easier to read because list() allows us to assign names to. | Using Arrays 75 Chapter 3 This line uses each to take the current element from prices return it as an array and make the next element current. It also uses list to turn the 0 and 1 elements from the array returned by each into two new variables called product and price. We can loop through the entire prices array echoing the contents using this short script. while list product price each prices echo product - price br This has the same output as the previous script but is easier to read because list allows us to assign names to the variables. One thing to note when using each is that the array keeps track of the current element. If we want to use the array twice in the same script we need to set the current element back to the start of the array using the function reset . To loop through the prices array again we type the following reset prices while list product price each prices echo product - price br This sets the current element back to the start of the array and allows us to go through again. Multidimensional Arrays Arrays do not have to be a simple list of keys and values each location in the array can hold another array. This way we can create a two-dimensional array. You can think of a two dimensional array as a matrix or grid with width and height or rows and columns. If we want to store more than one piece of data about each of Bob s products we could use a two-dimensional array. Figure shows Bob s products represented as a two-dimensional array with each row representing an individual product and each column representing a stored product attribute. 3 Using Arrays Code Description Price TIR Tires 100 OIL Oil 10 SPK Spark Plugs 4 --------------------------- product attribute Figure We can store more information about Bob s products in a two-dimensional array. 76 Using PHP Part I Using PHP we would write the following code to set up the data in the array shown in Figure . products array array TIR array OIL array SPK Tires 100 Oil 10 Spark Plugs

TỪ KHÓA LIÊN QUAN
Đã 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.