wordpress CMS主题 微信
Home > 网站建设 > PHP array traversal methods

PHP array traversal methods

高时银博客 网站建设 点击: 1,723 次 0 0

In PHP, how to traverse the array? Is it right? With C language, using a for loop to iterate over? The answer is: no.. In PHP, method of traversing arrays than in the C language is much more simple. Method for traversing arrays in PHP mainly has the following 2.

1, the foreach circulation method.

This is the most used in PHP array traversal.

Syntax structure: foreach (array as $value) or foreach (array as $key=>$value)

Array arrays are represented here, $key represents an array of keys, $valuevalue. To have a look through the example below:

$a=array(1,199,"abd",9);foreach($a as $key=> $value){echo "\$a[".$key."]=".$value."<br>";

}

The output results:

$a[0]=1$a[1]=199$a[2]=abd$a[3]=9

The following example is a two dimensional array:

$a=array(array("two"=>3,3),array("five"=>"hao",1));foreach($a as $key=> $value){foreach($value as $k=>$v)

{

echo "\$a[".$key."][".$k."]=".$v."<br>";

}

}

The output results:

$a[0][two]=3$a[0][0]=3$a[1][five]=hao$a[1][0]=1

Note: if a 2D array also contain other elements, such as: $a=array (2, array,"one" ("=>3,3 two", "love"), array ("Five" = > "Hao", 1)) the blue character elements. Use foreach traversal of will.

2, while (list ($key, $value) =each (array)) cyclic traversal method.

We look at the examples:

$a=array(array("two"=>3,3),array("five"=>"hao",1));while(list($key,$value)=each($a)){while(list($k,$v)=each($value))

{

echo "\$a[".$key."][".$k."]:".$v."<br>";

}

}

The output results:

$a[0][two]:3$a[0][0]:3$a[1][five]:hao$a[1][0]:1

Here we use the list () function and each () function. Each (array) returns onearray, as the following example:

$a=array ("=>3,3 two", "Five" = "Hao"); print_r (each ($a));

Results: Array ([1] = 3 [value] = > 3 [0] = > two [key] = > two)

While the list () function can be used to receive the each () function in the keyand key, and only accept each () function returns the number keys in the array.Through the while to scan the array, the each () function will continue to return a new array, and the list () function will continue to receive. Reach the traversal of the objective.

Prompt.

The difference between foreach and while traversal traversal is: an array of"read" operation using the foreach speed, obvious effect of large data; for an array of "write" operation using the while speed.


文章作者:高时银博客
本文地址:http://wanlimm.com/77201404041852.html
版权所有 © 转载时必须以链接形式注明作者和原始出处!

目前还没有评论。赶快来坐沙发吧。

发表评论