介紹
正常我們的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
*/
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。