Home > php教程 > php手册 > body text

php 遍历多维数组方法

WBOY
Release: 2016-06-13 09:48:07
Original
1558 people have browsed it

在php中数组分类很多种,如一维数组,二维数组,三维或多维数组,下面我来给大家介绍php 遍历多维数组,有需要的朋友可参考。

在php遍历数组有三个函数foreach、each、list & each下面我们看它们是如何遍历多维数组的。

先看一个遍历二维数组

 代码如下 复制代码

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

?>

下面看遍历三维数组

例1

 代码如下 复制代码

 function arr_fun($arr){
       if(is_array($arr)){
         foreach($arr as $v){
            if(is_array($v)){
            arr_fun($v);
            }else{
            echo $v."
";
            }
         }
       }else{
         echo $arr."
";
       }
   }

例2

 代码如下 复制代码

/*
*  -------------------------------------------------
*   Url    : www.bKjia.c0m
*   Date   : 2011-03-09
*  -------------------------------------------------
*/
function arr_foreach ($arr)
{
 if (!is_array ($arr))
 {
  return false;
 }
 
 foreach ($arr as $key => $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 '

';<br>
print_r($arr1);<br>
echo '<pre class="brush:php;toolbar:false">';<br>
arr_foreach ($arr1);<br>
?>
<p>输出结果</p>
<p>Array<br>
(<br>
    [1] => Array<br>
        (<br>
            [0] => 11<br>
            [1] => 12<br>
            [2] => 13<br>
            [14] => Array<br>
                (<br>
                    [0] => 141<br>
                    [1] => 142<br>
                )<br>
        )<br>
    [2] => 2<br>
    [3] => 3<br>
    [4] => 4<br>
    [5] => 5<br>
)<br>
11<br>
12<br>
13<br>
141<br>
142<br>
2<br>
3<br>
4<br>
5</p>
Copy after login

利用list与each遍历二维数组

 代码如下 复制代码

$sports = array(
    'football' => 'good',
    'swimming' => 'www.bKjia.c0m',
    'running'  => 'not good'
);

while (list($key, $value) = each($sports)) {
    echo $key.": ".$value."
";
}
?>

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!