Home  >  Article  >  Backend Development  >  PHP递归遍历多维数组的两种方法

PHP递归遍历多维数组的两种方法

WBOY
WBOYOriginal
2016-06-20 13:01:122625browse

PHP递归遍历多维数组的两种方法,实例分析php数组遍历的相关技巧,对数组操作还不熟练的朋友可以参考下

<?php function get_array_elems($arr, $where="array"){
	while(list($key,$value)=each($arr)){
		if (is_array($value)){
			get_array_elems($value, $where."[$key]");
		} else {
			for($i=0; $i<count($value);$i++){
			echo $where."[$key]=".$value."<br>\n";
			}
		}
	}
}
get_array_elems($array);
?>

另一个更简洁的array_map()函数递归写法。

<?php function each_array($arr){
		if (is_array($arr)){
			array_map("each_array",$arr);
		} else {
			for($i=0; $i<count($arr);$i++){
				echo $arr[$i]."<br>\n";
			}
		}
	}
$array = array(array("1","2","3","4"),array("a","b","c"));
each_array($array);
?>


Statement:
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