php遍历数组的方法分享

前端之家收集整理的这篇文章主要介绍了php遍历数组的方法分享前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

PHP中数组分为两类: 数字索引数组和关联数组。
其中数字索引数组和C语言中的数组一样,下标是为0,1,2…
而关联数组下标可能是任意类型,与其它语言中的hash,map等结构相似。
方法1:foreach
<div class="codetitle"><a style="CURSOR: pointer" data="69959" class="copybut" id="copybut69959" onclick="doCopy('code69959')"> 代码如下:

<div class="codebody" id="code69959">
<?PHP
$sports = array(
'football' => 'good',
'swimming' => 'very well',
'running' => 'not good');
foreach ($sports as $key => $value) {
echo $key.": ".$value."
";
}
?>

输出结果:
football: good
swimming: very well
running: not good
方法2:each
<div class="codetitle"><a style="CURSOR: pointer" data="61673" class="copybut" id="copybut61673" onclick="doCopy('code61673')"> 代码如下:
<div class="codebody" id="code61673">
<?PHP
$sports = array(
'football' => 'good',
'running' => 'not good');
while (!!$elem = each($sports)) {
echo $elem['key'].": ".$elem['value']."
";
}
?>

输出结果:
football: good
swimming: very well
running: not good 方法3:list & each
<div class="codetitle"><a style="CURSOR: pointer" data="39647" class="copybut" id="copybut39647" onclick="doCopy('code39647')"> 代码如下:
<div class="codebody" id="code39647">
<?PHP
$sports = array(
'football' => 'good',
'running' => 'not good');
while (!!list($key,$value) = each($sports)) {
echo $key.": ".$value."
";
}
?>

输出结果:
football: good
swimming: very well
running: not good

原文链接:https://www.f2er.com/php/27270.html
遍历数组

猜你在找的PHP相关文章