引见
一般我们的foreach能够按递次把一维数组内里每一个 key => value 打印出来,然则假如是多维数组则须要轮回在嵌套轮回,或则递归完成,然则这些体式格局都不够天真,因为在不确定该数组是几维的情况下,不可能永无止境的嵌套轮回,假如采纳递归到能够处理,然则假如只想运用foreach悉数轮回出来该怎样完成?
体式格局一:采纳PHP自身自带的迭代器类RecursiveIteratorIterator
$test_arr = array(1,2,3,array(4,'aa'=>5,6,array(7,'bb'=>8),9,10),11,12); $arrayiter = new RecursiveArrayIterator($test_arr); $iteriter = new RecursiveIteratorIterator($arrayiter); //直接打印即可根据横向递次打印出来 foreach ($iteriter as $key => $val){ echo $key.'=>'.$val; } //效果 /* 0=>1 1=>2 2=>3 0=>4 aa=>5 2=>6 0=>7 bb=>8 4=>9 5=>10 4=>11 5=>12 */
体式格局二:本身完成一个类似于 RecursiveIteratorIterator 的迭代器类,完成多维数组横向打印功用
class foreachPrintfArr implements Iterator { //当前数组作用域 private $_items; private $_old_items; //保留每次实行数组环境栈 private $_stack = array(); public function __construct($data=array()){ $this->_items = $data; } private function _isset(){ $val = current($this->_items); if (empty($this->_stack) && !$val) { return false; } else { return true; } } public function current() { $this->_old_items = null; $val = current($this->_items); //假如是数组则保留当前实行环境,然后切换到新的数组实行环境 if (is_array($val)){ array_push($this->_stack,$this->_items); $this->_items = $val; return $this->current(); } //推断当前实行完成后是不是须要切回上次实行环境 //(1) 假如存在跳出继承实行 //(2) 假如不存在且环境栈为空,则示意当前实行到末了一个元素 //(3) 假如当前数组环境下一个元素不存在,则保留一下当前实行数组环境 $this->_old_items = $this->_items; //然后切换上次实行环境 $this->_items = array_pop($this->_stack) 继承轮回, 直到当前数组环境下一个 //元素不为空为止 while (1) { if (next($this->_items)) { prev($this->_items); break; } elseif (empty($this->_stack)) { end($this->_items); break; } else { end($this->_items); if (!$this->_old_items) $this->_old_items = $this->_items; $this->_items = array_pop($this->_stack); } } return $val; } public function next() { next($this->_items); } public function key() { // 因为 key() 函数实行在 current() 函数以后 // 所以在 current() 函数切换实行环境 , 会致使切换之前的实行环境末了一个 key // 变成切换以后的key , 所以 $this->_old_items 保留一下切换之前的实行环境 // 防备key打印失足 return $this->_old_items ? key($this->_old_items) : key($this->_items); } public function rewind() { reset($this->_items); } public function valid() { return $this->_isset(); } }
内部实行体式格局
1、foreach 轮回我们自定义的foreachPrintfArr类,会自动挪用内部这5个要领 valid()、rewind()、key()、next()、current() 我们只须要完成这几个要领即可.
2、挪用递次:
第1次 => rewind -> valid -> current -> key
第2次~n次 => next -> valid -> current -> key
$test_arr = array(1,2,3,array(4,'aa'=>5,6,array(7,'bb'=>8),9,10),11,12); $iteriter = new foreachPrintfArr($test_arr); foreach ($iteriter as $key => $val){ echo $key.'=>'.$val; } //效果: /* 0=>1 1=>2 2=>3 0=>4 aa=>5 2=>6 0=>7 bb=>8 4=>9 5=>10 4=>11 5=>12 */
引荐教程:PHP视频教程
以上就是php怎样轮回输出5维数组的细致内容,更多请关注ki4网别的相干文章!