PHP foreach Implementation traversal multidimensional array mode

Source: Internet
Author: User
This article mainly for you in detail the PHP foreach traversal multidimensional Array implementation method, with a certain reference value, interested in small partners can refer to

Introduced
Normally our foreach can print each key in a one-dimensional array in order and value, but if it is a multidimensional array it needs to be looped in a nested loop, or recursively, but these are not flexible enough because, in the case where the array is not certain in several dimensions, Never-ending nesting loops, if recursive to solve, but if only want to use foreach all loop out how to implement?

Implementation method One
The iterator class that comes with PHP itself 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);  Direct printing can be printed out in a horizontal order  ($iteriter as $key = + $val) {     echo $key. ' = '. $val;   }   Results/  *     0=>1    1=>2     2=>3    0=>4    aa=>5    2=>6    0=>7    Bb=>8    4=>9    5=>10    4=>11    5=>12 * *

Implementation Method Two
Implement a recursiveiteratoriterator-like iterator class that implements a multidimensional array cross-print function

Class Foreachprintfarr implements Iterator {//current array scope private $_items;    Private $_old_items;     Save each execution of the array environment stack 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 it is an array, save the current execution environment, and then switch to the new array execution Environment if (Is_array ($val)) {Array_push ($this->_stack, $this->_items);        $this->_items = $val;      return $this->current (); }//To determine if the current execution needs to be tangent back to the last execution Environment//(1) If there is a step out of execution//(2) if it does not exist and the environment stack is empty, then the last element is currently executed//(3) If the current array environment does not exist, save      The current execution array environment $this->_old_items = $this->_items; Then switch the last execution environment $this->_items = Array_pop ($this->_stack) to continue looping until a//element is not empty in the current array environment while(1) {if (Next ($this->_items)) {prev ($this->_items);        } elseif (Empty ($this->_stack)) {End ($this->_items);          } 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 () {///because the key () function executes after the current () function//So the current () function switches the execution environment, which causes the last key of the execution environment to switch before becomes the key after the switch, so $this->_old_items Save the execution environment before the switchover//To prevent key printing error return $this->_old_items?    Key ($this->_old_items): Key ($this->_items);    } Public Function Rewind () {Reset ($this->_items);    } public Function valid () {return $this->_isset (); }  }

Internal execution mode

1, the Foreach Loop our custom Foreachprintfarr class, will automatically call inside these 5 methods valid (), rewind (), key (), next (), current () we only need to implement these methods.

2. Sequence of Calls:
1th time, Rewind, valid
2nd time ~n, valid, next-----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;   }    Results:/   *    0=>1   1=>2   2=>3   0=>4   aa=>5   2=>6   0=>7   Bb=>8   4=>9   5=>10   4=>11   5=>12   * *

The above is the whole content of this article, I hope that everyone's study has helped.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.