PHP: Multidimensional Arrays
Array does not have to be a simple list of keys and values; each array element can contain another array as a value, which in turn can hold other arrays as well. In such a way you can create two-dimensional or three-dimensional array.
Imagine that you are an owner of a flower shop. One-dimensional array is enough to keep titles and prices. But if you need to keep more than one item of each type you need to use something different - one of the ways to do it is using multidimensional arrays. The table below might represent our two-dimensional array. Each row represents a type of flower and each column Ė a certain attribute.
To store data in form of array represented by preceding example using PHP, letís prepare the following code:
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 organize manual access to each element or make it by putting For loop inside another For loop:
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:
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 the 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 manualy:
You donít have to be limited by two dimensions: the same way as array elements can contain other arrays, these arrays, in their turn, can contain new arrays.
Three-dimensional array is characterized by height, width, and depth. If you feel comfortable to imagine two-dimensional array as a table, then imagine a pile of such tables. Each element can be referenced by its layer, row, and column.
If we classify flowers in our shop into categories, then we can keep data on them using three-dimensional array. We can see from the code below, that three-dimensional array is an array containing array of arrays:
As this array has only numeric indexes, we can use nested for loops to display it:
This way of creating multidimensional arrays allows to create four- and five-dimensional arrays. Syntax rules do not limit the number of dimensions, but the majority of practical tasks logically correspond to the constructions of three or less dimensions.
|Copyright © 2005-2007 www.WebCheatSheet.com All Rights Reserved.|