php遍历数组的方法分享

yipeiwu_com6年前PHP代码库
在PHP中数组分为两类: 数字索引数组和关联数组。
其中数字索引数组和C语言中的数组一样,下标是为0,1,2…
而关联数组下标可能是任意类型,与其它语言中的hash,map等结构相似。
方法1:foreach
复制代码 代码如下:

<?php
$sports = array(
'football' => 'good',
'swimming' => 'very well',
'running' => 'not good');
foreach ($sports as $key => $value) {
echo $key.": ".$value."<br />";
}
?>

输出结果:
football: good
swimming: very well
running: not good
方法2: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

方法3: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

相关文章

PHP中json_encode、json_decode与serialize、unserialize的性能测试分析

于是便联想到PHP中的对象怎么样序列化存储性价比最高呢?接着想到了之前同事推荐的JSON编码和解码函数。 据他所说,json_encode和json_decode比内置的serializ...

PHP图像处理之imagecreate、imagedestroy函数介绍

使用PHP的GD库处理图像时,必须对画布进行管理。创建画布就是在内存中开辟一块存储区域,以后在PHP中对图像的所有操作都是基于这个图布处理的,图布就是一个图像资源。在PHP中,可以使用i...

php实现的统计字数函数定义与使用示例

本文实例讲述了php实现的统计字数函数定义与使用方法。分享给大家供大家参考,具体如下: <?php //函数定义: function countWords($str){...

PHP提示Cannot modify header information - headers already sent by解决方法

本文实例讲述了PHP提示Cannot modify header information - headers already sent by解决方法,是进行PHP程序设计过程中经常会遇到...

PHP 图像尺寸调整代码

复制代码 代码如下: /********************** *@filename - path to the image *@tmpname - temporary path...