w3pop.com :: ÍøÂçѧԺ :: PHP :: PHP Êý×é
An array can store one or more values in a single variable name.
Êý×飨array£©µÄ×÷ÓÃÊÇ£ºÎªÒ»¸öͬÃû±äÁ¿´æ´¢Ò»¸ö»ò¶à¸öÖµ¡£
When working with PHP, sooner or later, you might want to create many similar variables.
µ±ÄãÊéдPHPʱ£¬Äã¶¼»á»ò¶à»òÉٵش´½¨¼¸¸ö¹ØÏµÏàÀàËÆµÄ±äÁ¿¡£
Instead of having many similar variables, you can store the data as elements in an array.
ΪÁ˱ÜÃâʹÓöà¸öÀàËÆ±äÁ¿£¨ÕâÑù¶ÔÄãµÄ¼ÇÒäºÍ³ÌÐò±àдÀ´Ëµ»áºÜÂé·³£©£¬Äã¿ÉÒÔ°ÑËùÓеÄÊý¾Ý·Ö±ð×÷Ϊһ¸öÔªËØ´æ´¢ÔÚÒ»¸öÊý×éÀï¡£
Each element in the array has its own ID so that it can be easily accessed.
Êý×éÖÐÿ¸öÔªËØ¶¼ÓÐ×Ô¼º¶ÀÁ¢µÄID£¬ÕâÑù±ãÓÚ·ÃÎÊ¡£
There are three different kind of arrays:
ÏÂÃæÁоÙÁ˲»Í¬ÖÖÀàµÄÊý×飺
A numeric array stores each element with a numeric ID key.
Êý×ÖÊý×éÖеÄÿ¸öÔªËØ°üº¬Ò»¸öÊý×ÖID¡£
There are different ways to create a numeric array.
ÏÂÃæÁоټ¸ÖÖ²»Í¬µÄ·½·¨À´´´½¨Ò»¸öÊý×ÖÊý×飺
In this example the ID key is automatically assigned:
Õâ¸öÀý×Ó£¬ÔªËصÄIDÊÇ×Ô¶¯Éú³ÉµÄ£º
$names = array("Peter","Quagmire","Joe");
|
In this example we assign the ID key manually:
Õâ¸öÀý×ÓÖÐÔªËØµÄIDÊÇÎÒÃÇÊÖ¶¯Éú³ÉµÄ£º
$names[0] = "Peter"; |
The ID keys can be used in a script:
ÕâÀïµÄID¹Ø¼ü´Ê¿ÉÒÔÓ¦ÓÃÓÚÒ»¸ö½Å±¾³ÌÐòµ±ÖУº
<?php $names[0] = "Peter"; echo $names[1] . " and " . $names[2] . |
The code above will output:
ÉÏÊö´úÂëÖ´Ðкó½«Êä³öÏÂÃæµÄ½á¹û£º
Quagmire and Joe are Peter's neighbors |
An associative array, each ID key is associated with a value.
Õâ¸öÊý×éÖеÄÿ¸öID¶¼ÊÇÓëÒ»¸öÖµÁªÏµÔÚÒ»¿é£¨¼´ËüÃÇÊÇÅäÌ׵ģ¬×éºÏÔÚÒ»¿éµÄ£©¡£
When storing data about specific named values, a numerical array is not always the best way to do it.
Èç¹ûij¸öÖµÒѱ»ÃüÃû£¬ÄÇôÎÒ¾ÍÔÙʹÓÃÊý×ÖÊý×éÀ´´æ´¢ËüµÄÖµ¾Í²»·½±ãÁË¡£
With associative arrays we can use the values as keys and assign values to them.
ͨ¹ýʹÓÃÁªºÏÊý×飬ÎÒÃÇ¿ÉÒ԰ѹؼü´Ê×÷Ϊ¶ÔÏ󣬲¢¸øËüÃǸ³Öµ¡£
In this example we use an array to assign ages to the different persons:
ÔÚÕâ¸öÀý×Óµ±ÖУ¬ÎÒÃÇͨ¹ýʹÓÃÒ»¸öÊý×鏸²»Í¬µÄÈËÖ¸¶¨Á˲»Í¬µÄÄêÁ䣺
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
|
This example is the same as example 1, but shows a different way of creating the array:
Õâ¸öÀý×ӺͰ¸Àý1ÀàËÆ£¬ËüʹÓÃÁËÁíÍâÒ»ÖÖ´´½¨Êý×éµÄ·½·¨£º
$ages['Peter'] = "32"; |
The ID keys can be used in a script:
ÕâÀïµÄID¹Ø¼ü´Ê¿ÉÒÔÔڽű¾³ÌÐòÖÐʹÓãº
<?php $ages['Peter'] = "32"; echo "Peter is " . $ages['Peter'] . " years old."; |
The code above will output:
ÉÏÊö´úÂëÖ´Ðкó½«Êä³öÏÂÃæµÄ½á¹û£º
Peter is 32 years old. |
In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on.
¶ÔÓÚÒ»¸ö¶àλÊý×éÀ´ËµÃ»£¬ÆäÖеÄÿ¸öÔªËØ¶¼¿ÉÒÔÊÓΪһ¸öÊý×飻ÕâЩ¶þ¼¶Êý×éÖеÄÿ¸öÔªËØÓÖ¿ÉÒÔÊÓΪһ¸öÊý×飬ÒÔ´ËÀàÍÆ¡£
In this example we create a multidimensional array, with automatically assigned ID keys:
ÔÚÕâ¸ö°¸Àýµ±ÖУ¬ÎÒÃǽ¨Á¢ÁËÒ»¸ö¶àλÊý×飬ËüµÄIDÊÇ×Ô¶¯Éú³ÉµÄ£º
$families = array |
The array above would look like this if written to the output:
ÉÏÊöÊý×éµÄÖ´Ðнá¹ûÈçÏ£º
Array |