SPL Iterator and Associative Array
| From: | Jason Karns | Date: | Sat, 03 Jun 2006 02:12:02 +0000 |
| Subject: | SPL Iterator and Associative Array | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-237309@lists.php.net to get a copy of this message | ||
I'm going to try my best to explain what I'm trying to do.
I have my own class that has an array member. This class itself implements
Iterator. One of the fields in the array is itself an array that I would
like to iterate over. Here's some code:
class Folio implements Iterator {
$projects = array(
array(
'title'=>"",
'clip'=>"",
'small'=>array('1','2','3')),
array(
'title'=>"",
'clip'=>"",
'small'=>array('0','1','2'))
);
function title($x){
return current($this->projects[$]['small']);
}
function smalls($x){
return $this->projects[$x]['small'];
}
}
And I'd like to do:
foreach($folio->smalls() as $s){
echo $folio->title();
}
However, at the moment, doing this doesn't increment through the 'small'
array. It loops the correct number of times. But it only prints the first
one. I assumed it was because it wasn't moving the internal array pointer.
So I tried making the method smalls return a reference. Doing that made the
following work perfectly:
reset($folio->smalls());
while($s = current($folio->smalls())){
echo $folio->small();
next($folio->smalls());
}
But trying the foreach loop printed the second, and third elements, then
tried to output one passed the end of the array.
From what I understand, foreach simply expands to
reset();
while($x=current())
{...; next();}
What do I do?
Jason Karns
~~~~~~~~~~~
The Ohio State University [www.osu.edu]
Computer Science & Engineering [www.cse.osu.edu]
Attachment: [application/x-pkcs7-signature] smime.p7s
Attachment: [application/x-pkcs7-signature] smime.p7s