高手讲解PHP遍历数组的方法

在PHP中数组分为两类:  数字索引数组和关联数组。其中数字索引数组和C语言中的数组一样,下标是为0,1,2…而关联数组下标可能是任意类型,与其它语言中的hash,map等结构相似。

下面介绍PHP中遍历关联数组的三种方法:

foreach

[c-sharp]
  1. <?php 
  2. $sports = array( 
  3.     'football' => 'good'
  4.     'swimming' => 'very well'
  5.     'running'  => 'not good' 
  6.     ); 
  7.      
  8. foreach ($sports as $key => $value) { 
  9.     echo $key.": ".$value."<br />"
  10. ?> 

程序运行结果:

football: good

swimming: very well

running: not good

each

<?php

$sports = array(

    'football' => 'good',

    'swimming' => 'very well',

    'running'  => 'not good'

);

while ($elem = each($sports)) {

    echo $elem['key'].": ".$elem['value']."<br />";

}

?>

程序运行结果:

football: good

swimming: very well

running: not good

list & each

<?php

$sports = array(

    'football' => 'good',

    'swimming' => 'very well',

    'running'  => 'not good'

);

while (list($key, $value) = each($sports)) {

    echo $key.": ".$value."<br />";

}

?>

程序运行结果:

football: good

swimming: very well

running: not good

posted @ 2012-04-22 20:21  龙铭洪官方网站  阅读(127)  评论(0编辑  收藏  举报