As you know arrays are a list of key and value pairs. In general the key used to be a number ( or a string in case of associative arrays ) and the value is any data type. And that is important as it means that a value can be an other array as well. So if you create an aeeay where the values are arrays as well then you made a multidimensional array. Of course the values in this internal array can be again a new array and so on.
Let's see an example. Suppose you want to store user informations. In this case you have a lot of users and each user has more properties like name, age, email, website and so on.
- John
- email : john@demo.com
- website : www.john.com
- age : 22
- password : pass
- Anna
- email : anna@demo.com
- website : www.anna.com
- age : 24
- password : pass
- Peter
- email : peter@mail.com
- website : www.peter.com
- age : 42
- password : pass
- Max
- email : max@mail.com
- website : www.max.com
- age : 33
- password : pass
Now let's see how to define such an array in PHP. You can do it in some smaller parts and in this case first you define the sub arrays and then add it to the main array as follows:
Code:
$user1 = array("email" => "john@demo.com",
"website" => "www.john.com",
"age" => "22",
"password" => "pass");
$user2 = array("email" => "anna@demo.com",
"website" => "www.anna.com",
"age" => "24",
"password" => "pass");
$user3 = array("email" => "peter@mail.com",
"website" => "www.peter.com",
"age" => "42",
"password" => "pass");
$user4 = array("email" => "max@mail.com",
"website" => "www.max.com",
"age" => "33",
"password" => "pass");
$userList = array("John" => $user1,
"Anna" => $user2,
"Peter" => $user3,
"Max" => $user4);
Of course you can do all of it in only one step like this:
Code:
"email" => "john@demo.com",
"website" => "www.john.com",
"age" => "22",
"password" => "pass"),
"Anna" => array(
"email" => "anna@demo.com",
"website" => "www.anna.com",
"age" => "24",
"password" => "pass"),
"Peter" => array(
"email" => "peter@mail.com",
"website" => "www.peter.com",
"age" => "42",
"password" => "pass"),
"Max" => array(
"email" => "max@mail.com",
"website" => "www.max.com",
"age" => "33",
"password" => "pass")
);
Displaying an element from a multidimensional array is not so complicated. You just need to define more keys when you want to access a given array value. You can do it like this:
Code:
echo "John is ".$userList["John"]["age"]." years old.";
However in some cases it would be fine to print all information about John. You can do this as follows:
Code:
foreach ($userList["John"] as $key=>$value) {
echo "John $key - $value <br/>";
}
And the last variation is if you want to display all information from the array. In this case it's the best to create nested loops like this:
Code:
No comments:
Post a Comment