foreach来访问, 遍历的顺序是固定的么? 以什么顺序遍历呢?
比如:
代码如下
例2
$capitals= array(ohio=> columbus,towa=> des moines,arizona=> phoenix);
foreach($capitals as $key=> $val){
//add your codes
}
while()
while() 通常和 list(),each()配合使用。
#example2:
代码如下
显示结果:
other list of red.
other list of blue.
other list of green.
other list of yellow.
3. for()
#example3:
代码如下
zero,1 => one,2 => two);
for ($i = 0;$i $str = $arr[$i];
echo the number is $str.
;
}
?>
显示结果:
the number is zero.
the number is one.
the number is two.
========= 以下是函数介绍 ==========
key()
mixed key(array input_array)
key()函数返回input_array中位于当前指针位置的键元素。
#example4
代码如下
columbus,towa => des moines,arizona => phoenix);
echo
can you name the capitals of these states?
;
while($key = key($capitals)) {
echo $key.
;
next($capitals);
//每个key()调用不会推进指针。为此要使用next()函数
}
?>can you name the capitals of these states?
ohio
towa
arizona
each() 函数遍历数组
例子 1
代码如下
输出:
array ( [1] => peter [value] => peter [0] => 0 [key] => 0 )
子 2
each() 经常和 list() 结合使用来遍历数组。本例与上例类似,不过循环输出了整个数组:
代码如下
复制代码
$val
;
}
?>
输出:
0 => peter
1 => joe
2 => glenn
3 => cleveland
多维数组的递归遍历
代码如下
$val )
{
if (is_array ($val))
{
arr_foreach ($val);
}
else
{
echo $val.'
';
}
}
}
$arr1 = array (1=>array(11,12,13,14=>array(141,142)),2,3,4,5);
echo '
';
print_r($arr1);
echo '';arr_foreach ($arr1);
?>
结果
array
(
[1] => array
(
[0] => 11
[1] => 12
[2] => 13
[14] => array
(
[0] => 141
[1] => 142
)
)
[2] => 2
[3] => 3
[4] => 4
[5] => 5
)
11
12
13
141
142
2
3
4
5
http://www.bkjia.com/phpjc/371384.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/371384.htmltecharticleforeach来访问, 遍历的顺序是固定的么? 以什么顺序遍历呢? 比如: 代码如下 ?php $colors= array('red','blue','green','yellow'); foreach ($colors as $color){ //...