Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next Iterator method for associative Array

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?

like image 833
Alex Avatar asked Jun 17 '12 20:06

Alex


People also ask

How do you loop through a multidimensional associative array in PHP?

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.

How do you write associative 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.

What is meant by associative 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.


2 Answers

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;
}
like image 64
goat Avatar answered Sep 28 '22 07:09

goat


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

like image 24
shadyyx Avatar answered Sep 28 '22 05:09

shadyyx