its good that there is iterator to array http://php.net/manual/en/function.iterator-to-array.php but is there anything to do it reversed?
Asked
Active
Viewed 7,840 times
4
-
2from the page you linked `$iterator = new ArrayIterator($array)` – Steve May 27 '16 at 14:23
-
1What do you mean by do it reversed? – Chin Leung May 27 '16 at 14:24
-
@ChinLeung: o not convert iterator to array BUT convert array to iterator – John Smith May 27 '16 at 14:25
-
1http://php.net/manual/en/class.arrayobject.php maybe – JustOnUnderMillions May 27 '16 at 14:26
-
1Can you provide an example of an input and expected output via `print_r()` or `var_dump()`? I am 99% sure that PHP has some obscure function for this or if not then it is trivial via a `for()`/`foreach()` loop. – MonkeyZeus May 27 '16 at 14:28
2 Answers
8
Yes, if reversed means just make an Iterator from a given Array.
$array = array(
'a' => 1,
2 => new stdClass,
3 => array('subArrayStuff'=>'value')
);
$iterator = new ArrayObject($array);
$arrayAgain = iterator_to_array($iterator);
Try it.
http://php.net/manual/en/class.arrayobject.php
Please read also Difference between ArrayIterator, ArrayObject and Array in PHP.
apaderno
- 28,547
- 16
- 75
- 90
JustOnUnderMillions
- 3,741
- 9
- 12
-
1example works, and the question itself does not going so far that i would explain that too ;-) Question woulde be: What kind of `Traversable` do you want to use in the first place? ;) – JustOnUnderMillions May 27 '16 at 14:56
-
1I thing the `iterator_to_array` handles that `getIterator()` problem internally . So it would be fine :) – JustOnUnderMillions May 27 '16 at 15:02
-
1
0
http://php.net/manual/en/class.iterator.php Here's an example of MyIterator that uses an array. You can change the constructor and pass there any array
class myIterator implements Iterator {
private $position = 0;
private $array = array();
public function __construct($data = array()) {
$this->array = $data;
$this->position = 0;
}
function rewind() {
var_dump(__METHOD__);
$this->position = 0;
}
function current() {
var_dump(__METHOD__);
return $this->array[$this->position];
}
function key() {
var_dump(__METHOD__);
return $this->position;
}
function next() {
var_dump(__METHOD__);
++$this->position;
}
function valid() {
var_dump(__METHOD__);
return isset($this->array[$this->position]);
}
}
Richard
- 1,045
- 7
- 11
-
1A little cheeky copying the manual page, when a comment with a link would have achieved the same thing – RiggsFolly May 27 '16 at 14:31
-
2I've made the changes. Otherwise I would left the link in the comment. But yeah, it's based on copying from manual – Richard May 27 '16 at 14:32