Multi-Dimensional Arrays
There are times when you will want to include arrays within your array or represent something more two-dimensional than a simple list of data. Fortunately, PHP supports this functionality with easy-to-use multi-dimensional arrays.
Since the value of an array element can be anything, it can also be another array. This is how multi-dimensional arrays are created.
<?php
$bikes = array();
$bikes["Tourmeister"] = array("name" => "Grande Tour Meister",
"engine_cc" => 1100,
"price" =>12999);
$bikes["Slasher1000"] = array("name" => "Slasher XYZ 1000",
"engine_cc" => 998,
"price" => 11450);
$bikes["OffRoadster"] = array("name" => "Off-Roadster",
"engine_cc" => 550,
"price" => "4295");
?>
You can access the elements in a multi-dimensional array by putting pairs of square brackets next to each other in code:
<?php
$names = array_keys($bikes);
foreach ($names as $name)
{
print $bikes[$name] . " costs: " . $bikes[$name]["price"]
. "<br/>\n";
}
?>
Another helpful way to create multi-dimensional arrays would be to use the array_fill method. This creates an array for you where all the (integer-keyed) values have the same initial value. If we wanted to create a 3x3 matrix, we could use array_fill method, which takes three arguments: the starting index to use, the number of elements to create, and the value to put in each element. By having this value returned by array_fill, we can quickly create a two-dimensional array full of them:
<?php
$threex3matrix = array_fill(0, 3, array_fill(0, 3, 1));
foreach($threex3matrix as $row)
{
echo "{$row[0]} {$row[1]} {$row[2]}<br/>\n";
}
?>
The output would be
1 1 1
1 1 1
1 1 1
The count method can optionally be given one more parameter, COUNT_RECURSIVE, which is how we count all of the elements in multi-dimensional arrays. This parameter value tells the function to count the number of values in the arrays contained within the counted array.
<?php
$colors = array("non-colors" => array("white", "black"),
"primary" => array("blue", "yellow", "red"),
"happy" => array("pink", "orange"));
$elems = count($colors, COUNT_RECURSIVE);
//
// The following prints out 10 (3 top-level items in
// $colors containing a total of 7 sub-items)
//
echo "\$colors has a total of $elems elements<br/>\n";
?>
|