Friday, 08 Feb 2008 6:04PM EST
PHP: Multidimentional Arrays
PHP's associative arrays are very powerful in that they allow you to create arbitrary key values, rather than using the simple 0,1,2,3... that most programming languages force on you. For example, if you wanted to create a simple PHP array containing just 2 columns of information, an associative array would be perfect. Take the following 1 dimensional table of data about a pet:| Type | Name | Breed |
| Dog | Lassie | Collie |
To represent this with an associative array:
$pets = array("Type"=>"Dog", "Name"=>"Lassie", "Breed"=>"Collie");
| Animal | Name | Breed |
| Dog | Lassie | Collie |
| Fish | Nemo | Clown Fish |
| Cat | Garfield | Orange Tabby |
You could, of course, create 3 separate arrays; one for each animal. That method is very inefficient, though, and becomes impractical as the table grows. To creat a 2 dimensional array you simply create an array of arrays:
$pets = array( array("Type"=>"Dog", "Name"=>"Lassie", "Breed"=>"Collie"),
array("Type"=>"Fish", "Name"=>"Nemo", "Breed"=>"Clown Fish"),
array("Type"=>"Cat", "Name"=>"Garfield", "Breed"=>"Orange Tabby"),
);
echo "I have a ".$pets[0]["Type"]." named ".$pets[0]["Name"].". It is a ".$pets[0]["Breed"].".
"; echo "I have a ".$pets[1]["Type"]." named ".$pets[1]["Name"].". It is a ".$pets[1]["Breed"].".
"; echo "I have a ".$pets[2]["Type"]." named ".$pets[2]["Name"].". It is a ".$pets[2]["Breed"].".
";
for($i=0; $i<count($pets); $i++) {
echo "I have a ".$pets[$i]["Type"]." named ".$pets[$i]["Name"].". It is a ".$pets[$i]["Breed"].".
";
}
$pets = array( array( array("Type"=>"Dog", "Name"=>"Lassie", "Breed"=>"Collie"),
array("Type"=>"Dog", "Name"=>"Pluto", "Breed"=>"Bloodhound"),
),
array( array("Type"=>"Fish", "Name"=>"Nemo", "Breed"=>"Clown Fish")
),
array( array("Type"=>"Cat", "Name"=>"Garfield", "Breed"=>"Orange Tabby"),
array("Type"=>"Cat", "Name"=>"Tom", "Breed"=>"Russian Blue")
),
);
for($i=0; $i<count($pets); $i++) {
for($j=0; $j<count($pets[$i]; $i++) {
echo "I have a ".$pets[$i][$j]["Type"]." named ".$pets[$i][$j]["Name"].". It is a ".$pets[$i][$j]["Breed"].".
";
}
}
















0 Comments So Far