I want to use an associative array with the PHP iterator:
http://php.net/manual/en/class.iterator.php
is it possible?
I defined these methods:
public function rewind(){
reset($this->_arr);
$this->_position = key($this->_arr);
}
public function current(){
return $this->_arr[$this->_position];
}
public function key(){
return $this->_position;
}
public function next(){
++$this->_position;
}
public function valid(){
return isset($this->_arr[$this->_position]);
}
the problem is it doesn't iterate correctly. I only get one element.
I think it's because of the ++$this->_position
code in the next() method which doesn't have any effect because _position is a string (key of the associative array).
so how can I go to the next element of this type of array?
You can simply use the foreach loop in combination with the for loop to access and retrieve all the keys, elements or values inside a multidimensional array in PHP.
Associative array will have their index as string so that you can establish a strong association between key and values. The associative arrays have names keys that is assigned to them. $arr = array( "p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115"); Above, we can see key and value pairs in the array.
In computer science, an associative array, map, symbol table, or dictionary is an abstract data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection. In mathematical terms an associative array is a function with finite domain.
function rewind() {
reset($this->_arr);
}
function current() {
return current($this->_arr);
}
function key() {
return key($this->_arr);
}
function next() {
next($this->_arr);
}
function valid() {
return key($this->_arr) !== null;
}
Why not creating an ArrayObject
from Your associative Array
? Then You can getIterator()
from this ArrayObject
and call key()
, next()
etc on it as You want...
Some example:
$array = array('one' => 'ONE', 'two' => 'TWO', 'three' = 'THREE');
// create ArrayObject and get it's iterator
$ao = new ArrayObject($my_array);
$it = $ao->getIterator();
// looping
while($it->valid()) {
echo "Under key {$it->key()} is value {$it->current()}";
$it->next();
}
ArrayObject
ArrayIterator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With